Java数据库增删改查(CRUD)操作是指在Java应用程序中对数据库进行创建(Create)、读取(Read)、更新(Update)和删除(Delete)操作。这些操作是数据库管理中最基本的操作。
Java数据库增删改查操作广泛应用于各种需要与数据库交互的应用程序中,如Web应用、桌面应用、移动应用等。
以下是一个使用JDBC进行数据库增删改查的简单示例:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "username";
private static final String PASSWORD = "password";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class AddExample {
public static void addData(String name, int age) {
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
try (Connection conn = DBUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ReadExample {
public static void readData(int id) {
String sql = "SELECT * FROM users WHERE id = ?";
try (Connection conn = DBUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Age: " + rs.getInt("age"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UpdateExample {
public static void updateData(int id, String newName) {
String sql = "UPDATE users SET name = ? WHERE id = ?";
try (Connection conn = DBUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, newName);
pstmt.setInt(2, id);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DeleteExample {
public static void deleteData(int id) {
String sql = "DELETE FROM users WHERE id = ?";
try (Connection conn = DBUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
通过以上示例代码和常见问题的解决方法,您可以更好地理解和实现Java数据库增删改查操作。
领取专属 10元无门槛券
手把手带您无忧上云