sql查询是否创建重复行?

gudnpqoy  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(395)

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();
        }
xmq68pz9

xmq68pz91#

如果,您使用代码作为测试,并且运行超过1次 without a primary key 在表中,它将添加多个重复记录。
尝试添加一列 id 作为int自动递增,并将两列 NameLastName 在里面 UniqueKey .
当使用相同的值运行超过一段时间时,此更改将引发异常,并且您可以使用 try/catch 捕获异常。

相关问题