In this example, a class is defined to obtain the Connection object.To load the driver, we will use mysql-connector-java-5.1.47 in the lib folder.
Source Code
1)DBConnection.
package com.createTable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
// Declares a connection object
private Connection dbConnection = null;
// Declare the load-driven string
private String driveString = "com.mysql.jdbc.Driver";
// The Url string for the database
private String urlMysqlString = "jdbc:mysql://localhost:3306/Test?useSSL=false";
public DBConnection() throws Exception {
// The load driver
Class.forName(this.driveString);
// Get a database connection object and assign it to the dbconnection
dbConnection = DriverManager.getConnection(urlMysqlString, "root",
"root");
}
public Connection getDbConnection() {
return this.dbConnection;
}
public void close() throws SQLException {
dbConnection.close();
}
}
2)
package com.createTable;
import java.sql.Connection;
import java.sql.Statement;
public class CreateTable {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// Get the Connection object through a custom class
Connection connection = new DBConnection().getDbConnection();
Statement statement = connection.createStatement();
// This is the Sql statement that creates the table
String sql = "create table testTable("
+ "Id char(20) not null primary key,"
+ "Name char(10) not null)";
statement.execute(sql);
connection.close();
}
}
Output:
This is the information for the table created after execution.
mysql> desc testtable;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| Id | char(20) | NO | PRI | NULL | |
| Name | char(10) | NO | | NULL | |
+-------+----------+------+-----+---------+-------+