[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

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

Posted on 2004-10-07
2
Medium Priority
?
304 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

What do responsible coders do? They don't take detrimental shortcuts. They do take reasonable security precautions, create important automation, implement sufficient logging, fix things they break, and care about users.
This article will show how Aten was able to supply easy management and control for Artear's video walls and wide range display configurations of their newsroom.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
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…

649 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