Java 使用executeUpdate向資料庫中建立表格

來源:互聯網
上載者:User

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);

 其它代碼都是一樣的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.