1. 程式人生 > 程式設計 >JDBC如何訪問MySQL資料庫

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";<em>//查詢資料</em>

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

以上就是JDBC如何訪問MySQL資料庫的詳細內容,更多關於JDBC訪問MySQL資料庫的資料請關注我們其它相關文章!