MySQL数据库中创建了一个名为MyDB的数据库。现在要在MySQL数据库MyDB中创建一个新表COFFEES。
CreateCoffees.java代码如下:
import java.sql.*;
public class CreateCoffees{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance(); /* 装载驱动程序 */
} catch (Exception e){
System.err.println(e.getMessage());
}
try{
Connection con;
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/MyDB?user=root"); /* 构造连接 */
Statement stmt;
stmt = con.createStatement(); /* 实例化变量 */
String createString = "CREATE TABLE COFFEES(" +
"COF_NAME VARCHAR(32)," +
"SUP_ID INTEGER," +
"PRICE FLOAT," +
"SALES INTEGER," +
"TOTAL INTEGER," +
"PRIMARY KEY (COF_NAME));"; /* 数据库创建语句 */
stmt.executeUpdate(createString); /* 绑定并执行SQL语句 */
stmt.close(); /* 关闭Statement对象 */
con.close(); /* 关闭连接 */
} catch(SQLException e){
System.err.println("SQL Excetption:" + e.getMessage());
}
}
}