java連線資料庫的步驟
阿新 • • 發佈:2019-01-02
在編寫程式的時候,連線資料庫是必不可少的,現在總結一下java連線資料庫的一些步驟
第一步:在所需要專案中引入mysql資料庫的驅動
第二步:在程式中 註冊驅動
1》new com.mysql.jdbc.Driver();
2》class.forname("com.mysql.jdbc.Driver")
第三步: 先定義變數,後使用
Connection conn = null;// 資料庫連線
Statement stmt = null;// 資料庫表示式
ResultSet rs = null;// 結果集
第四步:獲取資料庫的連線
conn = java.sql.DriverManager
.getConnection( "jdbc:mysql://localhost:3306/資料庫名字?useUnicode=true&characterEncoding=GBK",
"使用者名稱", “密碼”);
第五步:獲取表示式
stmt = conn.createStatement();
第六步:執行插入資料的 SQL
int row = stmt.executeUpdate("insert into 表名(username, password, age) values('張三', '1234', 20)");
System.out.println("插入了 " + row);
第七步:執行 SQL
rs = stmt.executeQuery("select * from 表名");
第八步:釋放資源,建議放在finally語句中確保都被關閉掉了
rs.close();
stmt.close();
conn.close();