JDBC訪問MySQL資料庫的步驟
匯入驅動包,加載具體的驅動類
- 導包:
- 新建一個Java Project檔案,在此檔案夾下新建Folder檔案命名lib(此檔案夾下放一些匯入的包)
- 將mysql-connector-java-xxxx.jar拖進來,右鍵Build Path → Add to Build Path;(這里我用的是mysql-connector-java-8.0.20.jar)
- 加載具體的驅動類:
Class.forName("com.mysql.cj.jdbc.Driver");
與資料庫建立連接connection
String url = "jdbc:mysql://localhost:3306/****?serverTimezone=UTC"; //****是你要訪問的資料庫是哪個,mysql版本5.0以上需要在后面加上serverTimezone=UTC //String url = "jdbc:mysql://localhost:3306/****?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"; String username = "****"; //資料庫的用戶名 String password = "****";//資料庫的密碼 Connection con = DriverManager.getConnection(url, username, password);
發送sql陳述句,執行sql陳述句(Statement)
- 增刪改操作:
Statement statement = connection.createStatement(); String sql = "insert into user values(1,'Jackage','857857')";//插入一條資料 int executeUpdate = statement.executeUpdate(sql);//回傳值表示改動了幾條資料
- 查詢操作:
String sql = "select name,password from user";//查詢資料 ResultSet rs = statement.executeQuery(sql);
處理結果集(查詢)
- 處理增刪改的結果:
if (executeUpdate > 0) {
System.out.println("操作成功!!!");
} else {
System.out.println("未發生改動!!!!");
}
- 處理查詢的結果:
while (rs.next()) {
String uname = rs.getString("name");
String upwd = rs.getString("password");
System.out.println(uname+ " " + upwd);
}
以上是JDBC訪問資料庫的簡單步驟,中間我們還需要拋例外
除了Class.forName() 拋出ClassNotFoundException,其余方法全部拋SQLException
最后還需要關閉connection、statement、rs
關閉順序與打開時的順序相反,同時也要拋出例外
try {
if(rs!=null)rs.close()
if(stmt!=null) stmt.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/73354.html
標籤:Java
上一篇:JAVA工程師簡歷模板
