温馨提示×

maven怎么实现数据库增删改查

小亿
122
2024-02-29 15:16:34
栏目: 大数据

要使用Maven实现数据库增删改查功能,您需要在Maven项目中添加数据库驱动依赖,然后编写数据库操作的代码。以下是一个简单的示例:

1、添加mysql数据库驱动依赖到pom.xml文件中:

```xml

mysql

mysql-connector-java

8.0.26

```

2、编写数据库操作的Java代码:

```java

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

public class DatabaseOperations {

private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";

private static final String USER = "username";

private static final String PASSWORD = "password";

public void insertData(String name, String email) {

try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {

String sql = "INSERT INTO users (name, email) VALUES (?, ?)";

try (PreparedStatement stmt = conn.prepareStatement(sql)) {

stmt.setString(1, name);

stmt.setString(2, email);

stmt.executeUpdate();

}

} catch (SQLException e) {

e.printStackTrace();

}

}

public void updateData(int id, String email) {

try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {

String sql = "UPDATE users SET email = ? WHERE id = ?";

try (PreparedStatement stmt = conn.prepareStatement(sql)) {

stmt.setString(1, email);

stmt.setInt(2, id);

stmt.executeUpdate();

}

} catch (SQLException e) {

e.printStackTrace();

}

}

public void deleteData(int id) {

try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {

String sql = "DELETE FROM users WHERE id = ?";

try (PreparedStatement stmt = conn.prepareStatement(sql)) {

stmt.setInt(1, id);

stmt.executeUpdate();

}

} catch (SQLException e) {

e.printStackTrace();

}

}

public void queryData() {

try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {

String sql = "SELECT * FROM users";

try (PreparedStatement stmt = conn.prepareStatement(sql);

ResultSet rs = stmt.executeQuery()) {

while (rs.next()) {

int id = rs.getInt("id");

String name = rs.getString("name");

String email = rs.getString("email");

System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);

}

}

} catch (SQLException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

DatabaseOperations db = new DatabaseOperations();

db.insertData("Alice", "alice@example.com");

db.updateData(1, "alice.new@example.com");

db.deleteData(1);

db.queryData();

}

}

```

这个示例代码演示了如何使用Maven项目实现数据库的增删改查功能。您需要根据自己的数据库连接信息修改URL、USER和PASSWORD参数,然后通过调用不同的方法实现相应的数据库操作。在main方法中,我们创建了DatabaseOperations对象并调用了insertData、updateData、deleteData和queryData方法来执行相应的数据库操作。

0