javaweb之eclipse工程連接mysql數據庫
准備工作:
1.在mysql官網下載mysqlconnection的jar包
輸入網址:mysql.com—點擊DOWNLOADS——下拉選擇MySQL Community (GPL) Downloads »——選擇Connector/J——下載后解壓——找到mysql-connector-java-8.0.22.jar
2.將mysql-connector-java-8.0.22.jar復制到當前javaweb工程
3.構建路徑:右擊當前項目——選擇Build Path——Configure Build Path——Libraries——AddJARs——將之前復制在lib文件下的mysql-connection導入——Apply and Close
看到如下則成功:
4.在src中創建com.mysqlconnection包和mysqlconnection類
進行連接
public class mysqlconnect {
public static void main(String[] args) {
//判斷驅動是否加載成功
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //固定語法
System.out.print("成功加載驅動!");//提示語
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.print("加載驅動失敗!");
e.printStackTrace();
}
//連接mysql
Connection con;
//localhost為主機名 3306為mysql的端口號 web:進行連接的目標數據庫
String url = "jdbc:mysql://localhost:3306/web?serverTimezone=UTC";
//登錄數據庫用戶名
String user = "root";
//登錄數據庫的密碼
String password = "password";
try {
con = DriverManager.getConnection(url,user,password); //將參數傳給驅動進行連接
if(!con.isClosed()) {
System.out.print("成功連接數據庫!");
//創建statement對象
Statement statement = con.createStatement();
//聲明一個sql語句查詢student表中所有信息
String sql = "select * from student";
ResultSet rs = statement.executeQuery(sql);
//循環輸出打印student表中的id name age
while (rs.next()){System.out.print(rs.getString("id"));
System.out.print("");
System.out.print(rs.getString("name"));
System.out.print("");
System.out.print(rs.getString("age"));
System.out.print("\t");}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}