使用Java连接MySQL数据库可以通过以下步骤实现增、删、查操作:
1、导入相关的依赖库。需要引入MySQL数据库的驱动库,可以在项目的build.gradle(或pom.xml)文件中添加如下依赖:
// build.gradle
dependencies {
implementation 'mysql:mysql-connector-java:8.0.26'
}
2、创建数据库连接。使用Java中的java.sql.Connection
接口来建立和数据库之间的连接,可以使用MySQL提供的com.mysql.cj.jdbc.Driver
类来注册数据库驱动。
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语句。
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数据库实现增、删、查操作的基本步骤。可以根据具体需求进行修改和扩展。