Sunday, February 17, 2008

Connect to a database and read from table

This example shows how to connect to a database, in this case a MS SQL Server database and read rows from a table.
It is assumed that the table has 3 columns and they all contains string-values (datatype char, varchar etc.).
To connect to another database type, just change the driver and url to match the specific type.

Note that you'll have to change some of the values to match your own environment(database, table, userid and password), and to make it work, you will have to download the jdbc driver from Microsoft and put it in your classpath.
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;

public class DBTest {

  Connection m_Connection = null;
  Statement m_Statement = null;
  ResultSet m_ResultSet = null;

  String m_Driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
  String m_Url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=MyDatabase";

  public DBTest() {

    //Load driver
    try {
      Class.forName(m_Driver);
    }
    catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }
  }

  public void doWork() {

    String query = "";

    try {
      //Create connection object
      m_Connection = DriverManager.getConnection(m_Url, "userid", "password");
      
      //Create Statement object
      m_Statement = m_Connection.createStatement();
      query = "SELECT * FROM MyTable";

      //Execute the query
      m_ResultSet = m_Statement.executeQuery(query);

      //Loop through the results
      while (m_ResultSet.next()) {

          System.out.print(m_ResultSet.getString(1));
          System.out.print(", ");
          System.out.print(m_ResultSet.getString(2));
          System.out.print(", ");
          System.out.print(m_ResultSet.getString(3));
          System.out.print("\n"); //new line
          
      }
   }
    catch (SQLException ex) {
      ex.printStackTrace();
      System.out.println(query);
    }
    finally {

      try {
        if (m_ResultSet != null)
          m_ResultSet.close();
        if (m_Statement != null)
          m_Statement.close();
        if (m_Connection != null)
          m_Connection.close();
      }
      catch (SQLException ex) {
        ex.printStackTrace();
      }
    }
  }

  public static void main(String[] args) {
    DBTest dbTest = new DBTest();
    dbTest.doWork();
  }
}
 
 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory