这篇文章主要介绍怎样通过JDBC Statement来创建一个表。
通过调用s
tatement.execute()方法来执行sql语句,语法如下:
- Statement statement = conn.createStatement();
-
// execute create SQL stetement
-
statement.execute(sql);
完整例子如下:
- package org.hnrsc.jdbc;
-
-
import java.sql.Connection;
-
import java.sql.DriverManager;
-
import java.sql.SQLException;
-
import java.sql.Statement;
-
-
public class JDBCConnectMySQL {
-
-
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
-
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/test";
-
private static final String DB_USER = "root";
-
private static final String DB_PASSWORD = "";
-
-
-
public static void main(String[] args) {
-
try{
-
createTable();
-
}catch(SQLException e){
-
System.out.println(e.getMessage());
-
}
-
}
-
-
private static void createTable() throws SQLException{
-
Connection conn = null;
-
Statement stmt = null;
-
-
String sql = "CREATE TABLE t_user("
-
"id int auto_increment primary key,"
-
"username varchar(50) NOT NULL,"
-
"password varchar(50) NOT NULL"
-
")";
-
-
try{
-
conn = getDBConnection();
-
stmt = conn.createStatement();
-
System.out.println(sql);
-
stmt.execute(sql);
-
System.out.println("Table \"t_user\" is created!");
-
}catch(SQLException e){
-
System.out.println(e.getMessage());
-
}finally{
-
if(stmt!=null){
-
stmt.close();
-
}
-
if(conn!=null){
-
conn.close();
-
}
-
}
-
-
-
}
-
-
private static Connection getDBConnection(){
-
Connection conn = null;
-
try{
-
Class.forName(DB_DRIVER);
-
}catch(ClassNotFoundException e){
-
System.out.println(e.getMessage());
-
}
-
try{
-
conn = DriverManager.getConnection(DB_CONNECTION,DB_USER, DB_PASSWORD);
-
}catch(SQLException e){
-
System.out.println(e.getMessage());
-
}
-
-
return conn;
-
}
-
-
}
运行结果:
CREATE TABLE t_user(id int auto_increment primary key,username varchar(50) NOT NULL,password varchar(50) NOT NULL)
Table "t_user" is created!
在数据库里可以看到创建的表结构如下:
mysql> use test
Database changed
mysql> show tables;
----------------
| Tables_in_test |
----------------
| t_user |
----------------
1 row in set (0.08 sec)
mysql> desc t_user;
---------- ------------- ------ ----- --------- ----------------
| Field | Type | Null | Key | Default | Extra |
---------- ------------- ------ ----- --------- ----------------
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(50) | NO | | NULL | |
| password | varchar(50) | NO | | NULL | |
---------- ------------- ------ ----- --------- ----------------
3 rows in set (0.12 sec)
阅读(945) | 评论(0) | 转发(0) |