SQL query create duplicate rows?

DB is successfully connected but i run the code and then in DB there are duplicate rows
Why?

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If, you using code as test, and you run more then 1 time without a primary key in table it’s will add multiples records duplicates.

Try add an column id as int autoincrement and put both columns Name and LastName in UniqueKey.

This changes will throws exception when run more then time with same values, and you have the use try/catch to capture exception.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x