Create Table
Firstly in this program we are going to establish the connection with
database and creating a table with some fields. If table name already exists then
we are displaying the message "Table already exists!".
Description of code:
Statement:
It is a interface. Statement object executes the SQL statement and returns the result it produces.
createStatement():
It is a method of Connection interface. which returns Statement
object. This method will compile again and again whenever the program
runs.
CREATE TABLE table_name(field_name):
An appropriate code used for creating a table with given field name.
executeUpdate(String table):
This method also executes SQL statement that may be INSERT, UPDATE OR
DELETE
statement are used in the code. It takes string types parameters for SQL statement.
It returns int.
Here is the code of program:
public class Test{
public static void main(String[] args) {
System.out.println("Table Creation Example!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driverName = "com.mysql.jdbc.Driver";
String userName = "sa";
String password = "sa";
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName, userName, password);
try{
Statement st = con.createStatement();
String table = "CREATE TABLE Employee(id integer, name varchar(10))";
st.executeUpdate(table);
System.out.println("Table creation process successfully!");
}
catch(SQLException s){
System.out.println("Table all ready exists!");
}
con.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
|
|