View RSS Feed

Java Database

Using the DriverManager Class

Rate this Entry
by , 03-10-2012 at 07:47 AM (1197 Views)
The “DriverManager” class provides a method “DriverManager.getConnection” that is called when connection to your DBMS. The following code explains the use of getConnection method.
Java Code:
public Connection getConnection()
    throws SQLException {
    Connection conn = null;
    Properties connectionProps = new Properties();
    connectionProps.put("user", this.userName);
    connectionProps.put("password", this.password);

    if (this.dbms.equals("mysql")) {
        conn = DriverManager.
            getConnection(
            "jdbc:" + this.dbms + "://" +
            this.serverName +
            ":" + this.portNumber + "/",
            connectionProps);
    } else if (this.dbms.equals("derby")) {
        conn = DriverManager.
            getConnection(
            "jdbc:" + this.dbms + ":" +
            this.dbName +
            ";create=true",
            connectionProps);
    }
    System.out.println("Connected to database");
    return conn;
}
The following are some examples of database URLs:

  1. MySQL: jdbc:mysql://localhost:3306/, Where “local host” is the server name which is hosting your database. Port number is 3306.
  2. Java DB: jdbc:derby:testdb;create=true, where testdb is the database name to connect to.Create=true gives instructions to the DBMS for making database.

Submit "Using the DriverManager Class" to Facebook Submit "Using the DriverManager Class" to Digg Submit "Using the DriverManager Class" to del.icio.us Submit "Using the DriverManager Class" to StumbleUpon Submit "Using the DriverManager Class" to Google

Categories
JDBC

Comments