使用JDBC進行MYSQL資料庫連接
一共有六個步驟
1. 加載注冊驅動
使用IDEA建立maven工程時,可以直接在pom檔案中進行mysql驅動包的匯入;若不使用maven進行jar包匯入,可自行進行添加;
MySQL驅動的maven坐標:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
在resources檔案夾下建立database.properties檔案,將資料庫資訊寫入:
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/zzu?serverTimezone=UTC&characterEncoding=utf-8
user = root
password = XXXX
在util工具類中,利用靜態代碼塊進行驅動的注冊
static{
pro = new Properties();
try{
pro.load(jdbcutils.class.getClassLoader().getResourceAsStream("database.properties"));
Class.forName(pro.getProperty("driver"));
}catch(Exception exce){
exce.printStackTrace();
}
}
2. 獲取連接
在util工具類中,利用靜態方法getConnection來生成資料庫連接
public static Connection getConnection(Connection conn){
if(conn == null){
try{
conn = DriverManager.getConnection(pro.getProperty("url"),
pro.getProperty("user"),pro.getProperty("password"));
}catch (Exception e){
System.out.println("獲取連接出錯");
}
}
return conn;
}
在主函式中,使用工具類util的靜態方法getConnection來獲取資料庫連接
Connection conn = null;
conn = jdbcutils.getConnection(conn);
3. 獲取PreparedStatement
利用獲取的conn連接來進行PreparedStatem獲取
PreparedStatement prop = conn.prepareStatement("select * from userinfo");
4. 執行SQL陳述句
使用prop進行SQL陳述句的執行
ResultSet rs = prop.executeQuery();
5. 遍歷結果集
使用ResultSet的next()方法來進行結果集的遍歷
//括號中的引數名稱與資料庫表的列名一一對應
while(rs.next()){
int id = rs.getInt("id");
String college = rs.getString("college");
String name = rs.getString("name");
int picId = rs.getInt("pic_id");
System.out.println(id + " " + college + " " + name + " " +picId );
}
6. 關閉連接
在最后進行資料庫連接的關閉
在工具類utils中進行資料庫關閉靜態方法的設計
//先開后關的原則
private static void connClose(Connection conn, ResultSet rs,PreparedStatement prep){
if(rs != null){
try{
rs.close();
}catch (SQLException exception){
exception.printStackTrace();
}finally {
rs = null;
}
}
if(prep != null){
try{
prep.close();
}catch (SQLException exception){
exception.printStackTrace();
}finally {
prep = null;
}
}
if(conn != null){
try{
conn.close();
}catch (SQLException exception){
exception.printStackTrace();
}finally {
conn = null;
}
}
}
通過以上六個步驟可以獲取到資料庫中的資料,注意資料庫配置中的驅動和URL時區問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/273184.html
標籤:MySQL
上一篇:linux安裝mysql
