0.引入驅動jar包

使用jdbc進行具體操作前,需要引入相關資料庫的jar包, 或者使用mave管理依賴

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.34.0</version>
</dependency>

1.載入驅動

Class.forName(DRIVER);

2.獲取資料庫連線物件

Connection conn=DriverManager.getConnection(URL);

3.建立(預處理)語句物件

普通語句物件

Statement stmt=conn.createStatement();

預處理語句物件

PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setXxx(int parameterIndex, Xxx x); // 引數索引從1開始

4.執行sql語句

普通語句物件執行sql

boolean b=stmt.execute(sql);
int i=stmt.executeUpdate(sql);
ResultSet resultSet=stmt.executeQuery(sql);

預處理語句物件執行sql

int i=pstmt.executeUpdate();
ResultSet resultSet=pstmt.executeQuery();

5.處理結果集

while(resultSet.next())
{
int id=resultSet.getInt("id");
String name=resultSet.getString("name");
}

6.關閉結果集,語句,連線

resultSet.close();
stmt.close();
conn.close();

jdbc工具類封裝

在類路徑下建立配置檔案

mysql.properties

DRIVER=com.mysql.cj.jdbc.Driver
URL=jdbc:mysql://localhost:3306/test
USER=root
PASSWORD=root

DBUtil.java

public class DBUtil
{
private static final String URL;
private static final String USER;
private static final String PASSWORD; private DBUtil(){} static
{
// 從properties檔案中載入配置資訊
ResourceBundle bundle=ResourceBundle.getBundle("mysql");
String DRIVER=bundle.getString("DRIVER");
URL=bundle.getString("URL");
USER=bundle.getString("USER");
PASSWORD=bundle.getString("PASSWORD"); try
{
Class.forName(DRIVER);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
} public static Connection getConnection() throws SQLException
{
return DriverManager.getConnection(URL,USER,PASSWORD);
}
}