MySQL table create using JDBC
- Monday, October 17, 2011, 7:32
- JDBC MySQL, JDBC Tutorial
- Add a comment
Creating table in MySQL using JDBC is not a big deal. The DBA uses DB front-end editors like Tod, phpMyAdmin etc to create a table in database visually. A java developer can also create a table using JDBC. Here we want to says that create a table using JDBC is not a good solution and its better to create the table using given front-end editors.
Description of program: 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!”.
package net.jdbctutorial.mysql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class MySQLCreateTable { public static void main(String[] args) { Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "stock_db"; String driverName = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "p@s$word"; try { Class.forName(driverName).newInstance(); con = DriverManager.getConnection(url + dbName, userName, password); try { Statement st = con.createStatement(); String table = "create table employee ( emp_name VARCHAR(20), emp_id INT, emp_sal DOUBLE)"; st.executeUpdate(table); System.out.println("Table creation process successfully!"); } catch (SQLException s) { System.out.println("Table all ready exists!"); } //close the connection con.close(); } catch (Exception e) { e.printStackTrace(); } }//main }//class

