java web项目中连接mysql数据库,javaweb之eclipse工程连接mysql数据库
javaweb之eclipse工程連接mysql數(shù)據(jù)庫(kù)
準(zhǔn)備工作:
1.在mysql官網(wǎng)下載mysqlconnection的jar包
輸入網(wǎng)址:mysql.com—點(diǎn)擊DOWNLOADS——下拉選擇MySQL Community (GPL) Downloads ?——選擇Connector/J——下載后解壓——找到mysql-connector-java-8.0.22.jar
2.將mysql-connector-java-8.0.22.jar復(fù)制到當(dāng)前javaweb工程
3.構(gòu)建路徑:右擊當(dāng)前項(xiàng)目——選擇Build Path——Configure Build Path——Libraries——AddJARs——將之前復(fù)制在lib文件下的mysql-connection導(dǎo)入——Apply and Close
看到如下則成功:
4.在src中創(chuàng)建com.mysqlconnection包和mysqlconnection類
進(jìn)行連接
public class mysqlconnect {
public static void main(String[] args) {
//判斷驅(qū)動(dòng)是否加載成功
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //固定語(yǔ)法
System.out.print("成功加載驅(qū)動(dòng)!");//提示語(yǔ)
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.print("加載驅(qū)動(dòng)失敗!");
e.printStackTrace();
}
//連接mysql
Connection con;
//localhost為主機(jī)名 3306為mysql的端口號(hào) web:進(jìn)行連接的目標(biāo)數(shù)據(jù)庫(kù)
String url = "jdbc:mysql://localhost:3306/web?serverTimezone=UTC";
//登錄數(shù)據(jù)庫(kù)用戶名
String user = "root";
//登錄數(shù)據(jù)庫(kù)的密碼
String password = "password";
try {
con = DriverManager.getConnection(url,user,password); //將參數(shù)傳給驅(qū)動(dòng)進(jìn)行連接
if(!con.isClosed()) {
System.out.print("成功連接數(shù)據(jù)庫(kù)!");
//創(chuàng)建statement對(duì)象
Statement statement = con.createStatement();
//聲明一個(gè)sql語(yǔ)句查詢student表中所有信息
String sql = "select * from student";
ResultSet rs = statement.executeQuery(sql);
//循環(huán)輸出打印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();
}
}
}
標(biāo)簽:javaweb,rs,eclipse,System,String,mysql,print,out
來(lái)源: https://www.cnblogs.com/clinch/p/14229130.html
總結(jié)
以上是生活随笔為你收集整理的java web项目中连接mysql数据库,javaweb之eclipse工程连接mysql数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c++坦克大战 代码免费复制(附源码)
- 下一篇: php小问题