用Java编写一段增删改查功能
时间: 2023-05-16 16:05:41 浏览: 60
的代码,实现对MySQL数据库中的数据进行操作。
以下是一个简单的Java代码示例,用于实现增删改查功能:
import java.sql.*;
public class MySQLDatabase {
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public MySQLDatabase() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public void insert(String name, int age, String address) {
try {
String sql = "INSERT INTO mytable (name, age, address) VALUES ('" + name + "', " + age + ", '" + address + "')";
stmt.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
public void update(int id, String name, int age, String address) {
try {
String sql = "UPDATE mytable SET name='" + name + "', age=" + age + ", address='" + address + "' WHERE id=" + id;
stmt.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
public void delete(int id) {
try {
String sql = "DELETE FROM mytable WHERE id=" + id;
stmt.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
public void selectAll() {
try {
String sql = "SELECT * FROM mytable";
rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age + ", Address: " + address);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
请注意,这只是一个简单的示例,实际应用中需要更多的错误处理和安全性检查。另外,数据库连接信息应该存储在配置文件中,而不是硬编码在代码中。