?
Solved

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

Posted on 2004-10-07
2
Medium Priority
?
292 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 1

Assisted Solution

by:kuldeep_bhayana
kuldeep_bhayana earned 500 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 500 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: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering 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

In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Make the most of your online learning experience.
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Simple Linear Regression
Suggested Courses

743 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