Java语言对MySQL数据库的增删改查,可以通过Java的JDBC(Java Database Connectivity) API来实现。
import java.sql.*;
public class AddData {
public static void main(String[] args) {
try {
// 建立与MySQL数据库的连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// 创建一个Statement对象
Statement stmt = conn.createStatement();
// 执行INSERT语句
String sql = "INSERT INTO mytable (column1, column2, column3) VALUES ('value1', 'value2', 'value3')";
int rowsAffected = stmt.executeUpdate(sql);
System.out.println(rowsAffected + "行数据已添加到数据库表中。");
// 关闭连接和Statement对象
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
import java.sql.*;
public class DeleteData {
public static void main(String[] args) {
try {
// 建立与MySQL数据库的连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// 创建一个Statement对象
Statement stmt = conn.createStatement();
// 执行DELETE语句
String sql = "DELETE FROM mytable WHERE column1 = 'value1'";
int rowsAffected = stmt.executeUpdate(sql);
System.out.println(rowsAffected + "行数据已从数据库表中删除。");
// 关闭连接和Statement对象
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
import java.sql.*;
public class UpdateData {
public static void main(String[] args) {
try {
// 建立与MySQL数据库的连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// 创建一个Statement对象
Statement stmt = conn.createStatement();
// 执行UPDATE语句
String sql = "UPDATE mytable SET column1 = 'new value' WHERE column2 = 'value2'";
int rowsAffected = stmt.executeUpdate(sql);
System.out.println(rowsAffected + "行数据已在数据库表中更新。");
// 关闭连接和Statement对象
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
import java.sql.*;
public class QueryData {
public static void main(String[] args) {
try {
// 建立与MySQL数据库的连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// 创建一个Statement对象
Statement stmt = conn.createStatement();
// 执行SELECT语句
String sql = "SELECT * FROM mytable";
ResultSet rs = stmt.executeQuery(sql);
// 遍历结果集并输出数据
while (rs.next()) {
String column1Value = rs.getString("column1");
String column2Value = rs.getString("column2");
String column3Value = rs.getString("column3");
System.out.println("column1: " + column1Value + ", column2: " + column2Value + ", column3: " + column3Value);
}
// 关闭连接、Statement对象和ResultSet对象
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
通过以上的代码示例,你可以在Java语言中实现对MySQL数据库的增删改查操作。请注意,示例代码中的连接字符串、用户名和密码需要根据你自己的MySQL数据库配置进行修改,以确保正确连接到你的数据库。
领取专属 10元无门槛券
手把手带您无忧上云