SQL 查询创建重复行?
SQL query create duplicate rows?
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();
}
如果您使用代码作为测试,并且您 运行 在 table 中 without a primary key
超过 1 次,它将添加多个重复记录。
尝试将列 id
添加为 int 自动增量并将列 Name
和 LastName
放入 UniqueKey
.
当 运行 次使用相同的值时,此更改将抛出异常,并且您可以使用 try/catch
来捕获异常。
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();
}
如果您使用代码作为测试,并且您 运行 在 table 中 without a primary key
超过 1 次,它将添加多个重复记录。
尝试将列 id
添加为 int 自动增量并将列 Name
和 LastName
放入 UniqueKey
.
当 运行 次使用相同的值时,此更改将抛出异常,并且您可以使用 try/catch
来捕获异常。