Solved

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

Posted on 2004-10-07
2
273 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Tembedded WB animatid gifs not animated on some pcs 2 84
Cygwin - GNU GPL License 1 37
Query Syntax 17 43
WordPress: Debugging from my Windows 10 Desktop 6 38
I know it’s not a new topic to discuss and it has lots of online contents already available over the net. But Then I thought it would be useful to this site’s visitors and can have online repository on vim most commonly used commands. This post h…
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
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 …

828 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