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();
  }
}
 
Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: