Solved

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

Posted on 2004-10-07
2
266 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
Comment Utility
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
Comment Utility
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
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 …

728 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now