Java 使用executeUpdate向資料庫中建立表格
一、建立mysql.ini檔案,配置如下
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/select_testuser=rootpass=123456
這樣以後修改資料庫的配置直接在mysql.ini檔案中修改。
二、編寫代碼
initParam方法: 獲得mysql.ini中的資料
createTale方法: 串連資料庫,並且executeUpdate執行sql語句。此例的sql檔案為建立表語句。
main方法: 傳入Sql語句。
class ExecuteDDL {private String driver;private String url;private String user;private String pass;Connection conn;Statement stmt;public void initParam(String paramFile) throws Exception {Properties props = new Properties();props.load(new FileInputStream(paramFile));driver = props.getProperty("driver");url = props.getProperty("url");user = props.getProperty("user");pass = props.getProperty("pass");}public void createTale(String sql) throws Exception{try {Class.forName(driver);conn = DriverManager.getConnection(url,user,pass);stmt = conn.createStatement(); stmt.executeUpdate(sql);} finally{if (stmt != null) {stmt.close();}if (conn != null) {conn.close();}}}/** * @param args * @throws Exception */public static void main(String[] args) throws Exception {// TODO Auto-generated method stubExecuteDDL ed = new ExecuteDDL();ed.initParam("src/mysql.ini");ed.createTale("create table student " +"(id int, " +"name varchar(50), " +"num varchar(20) )");System.out.println("Creating table success!");}
注意事項:傳入的Sql語句最好在MySql測試通過,並且傳入的mysql.int檔案的路徑必須正確。
當執行完畢後,在MySql的select_test資料庫中查看該Student表是否已經建立成功了。
三、使用executeUpdate方法,向表中插入資料。
將上面的建立表的Sql語句改為插入資料表的語句,執行executeUpdate方法,其結果就是想表中插入資料。
建立insertSql變數。
private static String insertSql = "insert into student values(1,'XiaoMing','06108787')";
執行插入語句。
ed.createTale(insertSql);
其它代碼都是一樣的。