This documentation is archived and is not being maintained.

How to: Use JDBC in an Application

Visual Studio 2005

A Java database connection (JDBC) is a database driver that enables you to connect to a database programmatically. You use the connection as a bridge between your application and the actual database.

Visual J# comes with an implementation of JDBC on top of ODBC [JDBC-ODBC bridge]. This bridge can provide application a way to connect to any database server having ODBC driver installed on client computer with Visual J#.

The first step sets up a data source name (DSN) for managing user ID and password credentials on the Northwind Access database. The second step uses the DSN and the JdbcOdbcDriver to connect to the database, and return data. The code names the driver, Class.forName("com.ms.jdbc.odbc.JdbcOdbcDriver"), and builds a connection string that names the DSN with server and authentication credentials, as follows: String url = "jdbc:odbc:vbuetools";

The last example executes the query. Using the while (rs.next()) statement, the code spins through the result sets and grabs the data. Once the data prints to the console, the con.close() statement closes the record set and drops the database connection.

To set up a data source name

  1. Click Start, point to Control Panel, point to Administrative Tools, and then click Data Sources (ODBC).

  2. From the Administrative Tools screen, select Data Sources.

  3. On the ODBC Data Source Administrator page, click the System DSN tab, and click Add.

  4. On the Create New Data Source page, select Driver do Microsoft Access (*.mdb), and click Finish.

    This indicates the type of database. For your own applications, be sure to choose the driver that matches your database. In the case of SQL Server, scroll through the list and choose the driver that matches your version of SQL server.

  5. On the ODBC Microsoft Access Setup page, in the Data Source Name box, type JDBCdsn, and click Select.

  6. Select the Northwind.mdb, and click OK.

  7. On the Microsoft SQL Server DSN Configuration page, click With Windows NT authentication using the network login ID.

    This option enables you to access the data using your NT user ID and password.

  8. Click Next.

  9. Verify the connection, and click OK.

    The ODBC Administrative Tool stores the server name and credentials in the JDBCdsn.dsn binary file. At run time, your J# code accesses this information for connecting to the database.

To access the data

  1. On the File menu, point to New, and click Project.

  2. Click Console Application, and in the Name box, type JDBC2.

  3. Replace the contents of the Program.jsl with the following code:

    import java.*;
    import java.sql.*;
    import java.util.*;
    import com.ms.jdbc.odbc.JdbcOdbcDriver;
    public class Connect{
    
        private java.sql.Connection  con = null;
        private ResultSet rs;
         
         // Constructor:
         public Connect(){}
    
        private void FindEmployee() throws SQLException, ClassNotFoundException
        {
            try
            {
                Class.forName("com.ms.jdbc.odbc.JdbcOdbcDriver");
                String url = "jdbc:odbc:JDBCdsn";
                con = DriverManager.getConnection(url, "", "");
                Statement stmt = con.createStatement();
                rs = stmt.executeQuery("Select EmployeeID, LastName,  Title from Employees");
                while (rs.next())
                {
                    //Column names: 
                    System.out.println(rs.getInt("EmployeeID") + " " + rs.getString("LastName") + " " + rs.getString("Title"));
                }
                if(con != null)
                    con.close();
                con = null;
            }
            catch (SQLException ex)
            {
                throw ex;
            }
            catch (ClassNotFoundException clex)
            {
                throw clex;
            }
        }
    
         private void closeConnection(){
              try{
                   if(con != null)
                        con.close();
                   con = null;
              }catch(Exception ex){
                   ex.printStackTrace();
              }
         }
        
         public static void main(String[] args) throws Exception
           {
              Connect myDbTest = new Connect();
              try
              {
                  myDbTest.FindEmployee();
              }
              catch (Exception ex)
              {
                ex.printStackTrace();
                System.out.println("Error Trace in getConnection() : " + ex.getMessage());
              
    }      
    }
    }
    
  4. In the code you just added, verify that the data source name matches the one you created with the Administrative Tools. For example:

    String url = "jdbc:odbc: JDBCdsn";
    
  5. Press F5 to compile and run the code.

    The program fetches each employee serial number, last name, and title from the Employees table of the Northwind database.

Security

For convenience, the database name can be stored in the DSN configuration. Proper care must be taken by the application to not hard code or store credentials in unsafe locations or less secure ways. For Web applications, be sure to encode, encrypt, or hash user IDs, passwords, and other database information.

See Also

Show: