By using CREATE TABLE query we can create table. Syntax To create a table with JDBC we need to follow these steps Example Output while run the above program will return following output
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( columns )
);
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTableExample {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/Mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to create a table
String query = "CREATE TABLE Employees("
+ "ID INT NOT NULL, "
+ "NAME VARCHAR (20) NOT NULL, "
+ "AGE INT NOT NULL, "
+ "SALARY DECIMAL (18, 2), "
+ "ADDRESS VARCHAR (25) , "
+ "PRIMARY KEY (ID))";
stmt.execute(query);
System.out.println("Table Created......");
}
}
Connection established......
Table Created......
How to Create Objects in Java?
Can we define a static constructor in Java?
Memory Allocation in Java
What is Method Overloading in Java ?
How to create a table in Java with JDBC Connection?
What is the difference between JDK and JRE?
What is the Difference between Path and ClassPath in java?
How to check Java version?
What is Instance variable?
Can we declare the main () method as final in Java?
Convert given time in String format to seconds
Can we overload the main method in Java?
What are the important features of Java 8?
Can we declare the main method as private in Java?
What is a Class/Static Variables?
Can we declare a static variable within a method in java?