In this example, we are discuss about table creation in the database using JDBC Batch process.
In this example, we are discuss about table creation in the database using JDBC Batch process.In this example, we are discuss about table creation in the database using JDBC Batch process.
First of all, we will create a java class BatchDatabaseTableCreation.java.
In this class we will create database connection as:
Connection connection =
null;
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection
("jdbc:mysql://localhost:3306/databasename","username","passsword");
Now we will used sequence of the step for Batch processing for alter database table.
1. Create Statement object using createStatement() method on the created Connection object as:
Statement stmt = connection.createStatement();
2. set auto commit is false using setAutoCommit() as:
connection.setAutoCommit(false);
3. Create MySql create table statement for create new table in the
database and add these statement in batch using addBatch() method as:
String createtablequery =
"CREATE TABLE user(user_id integer,
user_name varchar(20))";
stmt.addBatch(createtablequery);
4. Execute the MySql statements using executeBatch() method on created statement object as:
stmt.executeBatch();
5. Last commit the connection using commit() method as:
connection.commit();
The code of the BatchDatabaseTableCreation.java class is:
import java.sql.*; public class BatchDatabaseTableCreation { public static void main(String[] args) { try{ Connection connection = null; Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/roseindia_jdbc_tutorials", "root","root"); try{ // Create statement object Statement stmt = connection.createStatement(); // Set auto-commit to false connection.setAutoCommit(false); // create database query String createtablequery = "CREATE TABLE user(user_id integer, user_name varchar(20))"; stmt.addBatch(createtablequery); stmt.executeBatch(); System.out.println("Database Table Creation Sucessfully."); // connection committed connection.commit(); } catch (SQLException s){ System.out.println("SQL Exception " + s); } } catch (Exception e){ e.printStackTrace(); } } }
Now we will run this example with eclipse IDE.
Program output:
The eclipse console output is:
The database table is: