Solved

Can I get an example program of connecting to a database using Java?

Posted on 2004-10-07
2
269 Views
Last Modified: 2010-04-17
Is there a working example out there that I may use? Eventually I will have to connect to four databgases.    I'll be running the program in DOS or from a schedular.
Thank you
0
Comment
Question by:coolgem
2 Comments
 
LVL 1

Assisted Solution

by:kuldeep_bhayana
kuldeep_bhayana earned 125 total points
ID: 12256032
Hi,

I am providing here a sample for connecting to a Database and inserting a row in a table. The following code sample is a complete program that should run if you have a JDBC 2.0 Compliant driver that implements scrollable result sets.


import java.sql.*;

public class InsertRows {
    public static void main(String args[]) {
   
        final String url =  "jdbc:oracle:thin:username/password@(description=(
        address_list=(address=(protocol=tcp)
        (host=developer)(port=1521)))
        (source_route=yes)(connect_data=(sid=jdcsid)))";
       
        //GENERAL FORMAT FOR ABOVE URL: jdbc:mySubprotocol:myDataSource
        //mySubprotocol : database system specific
       //myDataSource  : the actual database

        Connection con;
       
        Statement stmt;
        try {
                                Class.forName("oracle.jdbc.driver.OracleDriver"); // LOAD DRIVER
              } catch(java.lang.ClassNotFoundException e) {
                                System.err.print("ClassNotFoundException: ");
                                System.err.println(e.getMessage());
             }
   
       try {
                               con = DriverManager.getConnection(url);
                               stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                                                                                   ResultSet.CONCUR_UPDATABLE);
                               ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");
                               uprs.moveToInsertRow();
                               uprs.updateString("COF_NAME", "Kona");
                               uprs.updateInt("SUP_ID", 150);
                               uprs.updateFloat("PRICE", 10.99f);
                               uprs.updateInt("SALES", 0);
                               uprs.updateInt("TOTAL", 0);
                               uprs.insertRow();
        uprs.updateString("COF_NAME", "Kona_Decaf");
        uprs.updateInt("SUP_ID", 150);
        uprs.updateFloat("PRICE", 11.99f);
        uprs.updateInt("SALES", 0);
        uprs.updateInt("TOTAL", 0);
        uprs.insertRow();
        uprs.beforeFirst();
        System.out.println("Table COFFEES after insertion:");
        while (uprs.next()) {
            String name = uprs.getString("COF_NAME");
            int id = uprs.getInt("SUP_ID");
            float price = uprs.getFloat("PRICE");
            int sales = uprs.getInt("SALES");
            int total = uprs.getInt("TOTAL");
            System.out.print(name + "   " + id + "   " + price);
            System.out.println("   " + sales + "   " + total);
        }

        uprs.close();
        stmt.close();
        con.close();

    } catch(SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}


0
 

Accepted Solution

by:
huyntminh earned 125 total points
ID: 12256037
In this example, I will use mysql database. If you want to run this you should first download and reference to a MySql driver.
You could refer to this link for more information in MySQL driver: http://www.cs.wcupa.edu/~rkline/mysql-java-win.php
For other DB, you could search them on the google for driver.

package DataExecutive;

import java.sql.*;
import javax.swing.table.TableModel;


public class Executive {
  private static String msDriver = "com.mysql.jdbc.Driver";
  private static String msDatabase = null;
  private String msConnectionURL = null;
  private String msUsername = null;
  private String msPassword = null;
  private Connection moConn = null;
  private ResultSet moRs = null;

  public Executive() {
    try {
      this.loadDriver(msDriver);
      moConn = DriverManager.getConnection(msConnectionURL, msUsername,
                                           msPassword);
    }catch (Exception ex){
      ex.printStackTrace();
    }
  }

  public Executive(String connectionURL, String UserName, String Password) {
    msConnectionURL = connectionURL;
    msUsername = UserName;
    msPassword = Password;
    try {
      this.loadDriver(msDriver);
      moConn = DriverManager.getConnection(msConnectionURL, msUsername,
                                           msPassword);
    }catch (Exception ex){
      ex.printStackTrace();
    }
  }

  public String getConnectionURL() {
    return msConnectionURL;
  }

  public void setConnectionURL(String ConnectionURL) {
    msConnectionURL = ConnectionURL;
  }

  public void setUserName(String UserName) {
    msUsername = UserName;
  }

  public void setPassword(String Password) {
    msPassword = Password;
  }

  public void setDatabaseName(String Name){
    msDatabase = Name;
  }

  public static String loadDriver(String DriverName){
    String sErr = null;
    try {
      Class.forName(DriverName).newInstance();
    }
    catch (Exception ex)
    {
      sErr = ex.toString();
      ex.printStackTrace();
    }
    return sErr;
  }

  public ResultSet ExecuteResultSet(String QuerryString, String Error) {
    ResultSet Rs = null;
    Statement stmt = null;
    try {
      stmt = moConn.createStatement();
      Rs = stmt.executeQuery(QuerryString);
      Error = null;
      return Rs;
    }
    catch (Exception ex) {
      Error = ex.getMessage();
      return null;
    }
  }

  public boolean ExecuteUpdate(String SQL, String Error){
    try {
      Statement stmt = moConn.createStatement();
      stmt.executeUpdate(SQL);
      stmt.close();
    }catch (Exception ex)
    {
      ex.printStackTrace();
      Error = ex.getMessage();
      return false;
    }
    return true;
  }

  public TableModel ExecuteTableModel(String QuerryString, String Error){
    try {
      ResultSet oRs = this.ExecuteResultSet(QuerryString, Error);
      TableModel oModel = new MyTableModel(oRs);
      return oModel;
    }
    catch (Exception ex){
      ex.printStackTrace();
      Error = ex.getMessage();
      return null;
    }
  }
}
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
strCopies  challenge 17 87
WMI, model #, retrieving information 10 139
Microsoft C++ code failing in executable that worked 9 97
C Programming - If Statement 8 76
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
Computer science students often experience many of the same frustrations when going through their engineering courses. This article presents seven tips I found useful when completing a bachelors and masters degree in computing which I believe may he…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question