Creating Connections with DataSource Class

This section describes how to create connection objects with the DataSource class.

Newer version of JDBC recommends now that connection objects should be created by the DataSource implementation class, com.mysql.jdbc.jdbc2.optional.MysqlDataSource. Here is a sample program that creates a connection object using the DataSource class without using JNDI services:

/**
 * MySqlDataSource.java
 * Copyright (c) 2015, HerongYang.com, All Rights Reserved.
 */
import java.sql.*;
import javax.sql.*;
public class MySqlDataSource {
  public static void main(String [] args) {
    Connection con = null;
    try {

// Setting up the DataSource object
      com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds 
        = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
      ds.setServerName("localhost");
      ds.setPortNumber(3306);
      ds.setDatabaseName("test");
      ds.setUser("root");
      ds.setPassword("TopSecret");

// Getting a connection object
      con = ds.getConnection();
      
// Getting database info
      DatabaseMetaData meta = con.getMetaData();
      System.out.println("Server name: " 
        + meta.getDatabaseProductName());
      System.out.println("Server version: "
        + meta.getDatabaseProductVersion());

// Closing the connection
      con.close();
    } catch (Exception e) {
      System.err.println("Exception: "+e.getMessage());
    }
  }
}

The output confirms that I got a good connection. Remember to include mysql-connector-java-5.1.38-bin.jar in the classpath for compilation and execution:

C:\herong>javac -cp .;\local\lib\mysql-connector-java-5.1.38-bin.jar
  MySqlDataSource.java

C:\herong>java -cp .;\local\lib\mysql-connector-java-5.1.38-bin.jar
  MySqlDataSource

Server name: MySQL
Server version: 5.7.10-log

Last update: 2015.

Table of Contents

 About This Book

 Introduction of SQL

 MySQL Introduction and Installation

 Introduction of MySQL Programs

 Perl Programs and MySQL Servers

 PHP Programs and MySQL Servers

Java Programs and MySQL Servers

 MySQL Connector/J - Download and Installation

 Loading JDBC Driver Class - com.mysql.jdbc.Driver

 JDBC Driver Connection URL

Creating Connections with DataSource Class

 Getting Driver and Server Information

 Creating Tables with AUTO_INCREMENT Columns

 "INSERT INTO" Statements

 Datatypes and Data Literals

 Operations and Expressions

 Character Strings and Bit Strings

 Commonly Used Functions

 Table Column Types for Different Types of Values

 Using DDL to Create Tables and Indexes

 Using DML to Insert, Update and Delete Records

 Using SELECT to Query Database

 Transaction Management and Isolation Levels

 Locks Used in MySQL

 Defining and Calling Stored Procedures

 Variables, Loops and Cursors Used in Stored Procedures

 Outdated Tutorials

 References

 PDF Printing Version