简体   繁体   中英

How to ensure INSERT INTO wont add the same value on the mySQL DB

Is there a way to make an INSERT INTO prepared statement but make sure the name the user will give wont be put on the DB if it already exists?

public ServerConn(String sql_name,int sql_year,String sql_ticket)
  {
   try
        {
           Class.forName( "com.mysql.jdbc.Driver" ) ;
           java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/promitheas?user=gunner&password=1234") ;
           this.sql_name = sql_name;
           this.sql_year = sql_year;
           this.sql_ticket = sql_ticket;
           PreparedStatement ps = conn.prepareStatement("INSERT INTO tickets (xronia,ticket,name) VALUES (?,?,?)");
           ps.setInt(1,sql_year);
           ps.setString(2,sql_ticket);
           ps.setString(3,sql_name);
           ps.executeUpdate();
           System.out.println("Done!");
   } catch (SQLException case1){
         case1.printStackTrace();
   } catch(Exception case2){
         case2.printStackTrace();
 }
}

You can check this on the database by adding a unique constraint like this :

ALTER TABLE tickets ADD UNIQUE (name)

The INSERT won't be possible if the name already exists in the database.

Make the row unique in the database? If you try to insert identical data you should get a message telling you that the data already present and can not be stored because only unique data can be inserted.

This can be done by in different ways. You could create a unique constraint or you could just write another query to check whether the data already exists in the database:

ResultSet rs = query ("SELECT * FROM table_name WHERE conditions" + ";");
if (rs.next() )
//it exists in the table already

Two choices for resolving it :

  • alter the table and add unique constraint on this column

  • add some codes before the opertion insert. And the goal of the new codes is to validate the name dosen't exist in the actual table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM