JAVA操作MySQL資料庫,涉及創建連接,創建表,插入資料,更新資料,查詢資料,
總體步驟:
1) 獲取驅動(可以省略) 2) 獲取連接Connection 介面,代表一個連接物件 ,具體的實作類由資料庫的廠商實作 使用 DriverManager類的靜態方法,getConnection可以獲取資料庫的連接 3) 獲取Statement物件
通過Connection 的 createStatement方法 獲取sql陳述句執行物件 4) 處理結果集(只在查詢時處理) 5) 釋放資源
package jdbc; import java.sql.*; public class Test01 { public static void main(String[] args) throws ClassNotFoundException, SQLException {
//使用驅動; Class.forName("com.mysql.jdbc.Driver");
// 創建連接,涉及資料庫IP,埠,資料庫名,字符集,賬號及密碼 String url = "jdbc:mysql://127.0.0.1:3307/testdb?characterEncoding=UTF-8"; Connection conn = DriverManager.getConnection(url,"root","Root#123456"); //System.out.println(conn); // 獲取陳述句執行平臺物件 Statement Statement smt = conn.createStatement(); // 創建表 executeUpdate方法 String sql1 = "create table if not exists test14(id int primary key auto_increment ,name varchar(20),age int);"; smt.executeUpdate(sql1); // 插入資料 String sql_i = "insert into test14 values(1,'劉備',45),(2,'關羽',40),(3,'張飛',37),(4,'趙云',30),(5,'諸葛亮',27);"; smt.executeUpdate(sql_i); // 更新資料 String sql_u= "update test14 set age = 36 where name='張飛';"; smt.executeUpdate(sql_u); // 查詢結果 String sql_q = "select * from test14;"; ResultSet res = smt.executeQuery(sql_q); while(res.next()){ int id = res.getInt(1); String name= res.getString("name"); int age = res.getInt("age"); System.out.println("id:"+ id + " name:" + name +" age:"+age); } // 關閉流 (先開后關) res.close(); smt.close(); conn.close(); } }
結果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/234605.html
標籤:Java
下一篇:List去重的五種方法
