【发布时间】:2021-09-17 22:23:08
【问题描述】:
DB 已成功连接,但我运行代码,然后在 DB 中有重复的行 为什么?
public class MySQLTest
{
public static void main(String[] args)
{
try {
Connection con=DriverManager.getConnection(url, username, password);
String sql = "INSERT INTO customer (firstname,lastname) VALUES (?,?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1,"Name");
statement.setString(2, "LastName");
int rows = statement.executeUpdate();
if (rows > 0 ) {
System.out.println("A row is inserted");
}
statement.close();
con.close();
}
【问题讨论】:
-
可能是因为您在测试时输入了多次名称。
-
如果你想停止这种情况,那么你必须使表中的一列或两列唯一,但是你将不得不处理从数据库返回的重复错误在你的 Catch 块中,并决定如何处理它