JDBC连接数据库并创建表

操作JDBC的步骤

1):加载注册驱动.

 

2):获取连接对象.

3):创建/获取语句对象

4):执行SQL语句

5):释放资源

 


 1 //创建一张学生表 2  @Test 3 public void testCreateTable() 4  { 5  6  7 //数据库连接对象 8 Connection conn = null; 9 //创建语句对象10 Statement st = null;11 //SQL语句12 String sql = "CREATE TABLE t_student1(id BIGINT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(20),age INT)";13 try {14 //jdk 1.6提到无需加载注册驱动15 //Class.forName("com.mysql.jdbc.Driver");16 //获取数据库连接对象17 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");18 //获取创建语句对象19 st = conn.createStatement();20 //执行SQL语句21 int rows = st.executeUpdate(sql);22 } catch (Exception e) {23 // TODO Auto-generated catch block24  e.printStackTrace();25  }26 27 //释放资源28 try {29 if(st!=null)30  st.close();31 } catch (Exception e) {32 // TODO Auto-generated catch block33  e.printStackTrace();34 }finally{35 try {36 if(conn!=null)37  conn.close();38 } catch (Exception e) {39 // TODO Auto-generated catch block40  e.printStackTrace();41  }42  }43 44 }

JDBC创建表

 

 

 

相关文章