使用Java連接MySQL數據庫可以通過以下步驟實現增、刪、查操作:
1、導入相關的依賴庫。需要引入MySQL數據庫的驅動庫,可以在項目的build.gradle(或pom.xml)文件中添加如下依賴:
```java
// build.gradle
dependencies {
implementation 'mysql:mysql-connector-java:8.0.26'
}
```
2、創建數據庫連接。使用Java中的`java.sql.Connection`接口來建立和數據庫之間的連接,可以使用MySQL提供的`com.mysql.cj.jdbc.Driver`類來注冊數據庫驅動。
```java
import java.sql.Connection;
import java.sql.DriverManager;
public class DatabaseConnection {
private static final String URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
System.out.println("Connected to the database successfully.");
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
```
3、實現增、刪、查操作。根據需要實現相應的方法,可以使用`java.sql.Statement`或`java.sql.PreparedStatement`來執行SQL語句。
```java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseOperations {
private static final String TABLE_NAME = "table_name";
public static void insertData(String data) {
try {
Connection connection = DatabaseConnection.getConnection();
Statement statement = connection.createStatement();
String sql = "INSERT INTO " + TABLE_NAME + " (column_name) VALUES ('" + data + "')";
statement.executeUpdate(sql);
System.out.println("Data inserted successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void deleteData(int id) {
try {
Connection connection = DatabaseConnection.getConnection();
Statement statement = connection.createStatement();
String sql = "DELETE FROM " + TABLE_NAME + " WHERE id = " + id;
statement.executeUpdate(sql);
System.out.println("Data deleted successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void retrieveData() {
try {
Connection connection = DatabaseConnection.getConnection();
Statement statement = connection.createStatement();
String sql = "SELECT * FROM " + TABLE_NAME;
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String data = resultSet.getString("column_name");
System.out.println("ID: " + id + ", Data: " + data);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在上述代碼中,`TABLE_NAME`是數據庫表的名稱,`column_name`是要進行操作的具體列名。
注意:在實際開發中,需要根據具體情況進行異常處理和資源釋放,例如在finally塊中關閉連接、釋放資源。
以上就是使用Java連接MySQL數據庫實現增、刪、查操作的基本步驟。可以根據具體需求進行修改和擴展。