本文介绍了com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:键“PRIMARY”的重复条目“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从今天起就得到这个例外。昨天的事情没事。我将发布我的代码:

  public void enterStaff()throws ClassNotFoundException,SQLException {
try {
的Class.forName( com.mysql.jdbc.Driver);
connect = DriverManager
.getConnection(jdbc:mysql:// localhost:3306 / project?
+user = root& password = virus);
statement = connect.createStatement();

preparedStatement = connect
.prepareStatement(SELECT count(*)FROM information_schema.tables\\\

+WHERE table_schema ='project'AND table_name ='staff' );
rs = preparedStatement.executeQuery();
rs.next();
int chk = rs.getInt(1);

if(chk!= 1){
preparedStatement = connect
.prepareStatement(create table staff(staffname varchar(30)primary key););
preparedStatement.executeUpdate();
}

preparedStatement = connect
.prepareStatement(insert into staff values(?););
preparedStatement.setString(1,addSubName.getText());

preparedStatement.executeUpdate();
} catch(ClassNotFoundException | SQLException e){
throw e;
} finally {
close2();
}

}

private void close2(){
try {

if(statement!= null){
statement.close();
}

if(connect!= null){
connect.close();
}
} catch(SQLException e){

}
}

我正在尝试创建一个只有一列的列,该列是主键。当代码第一次运行时,表正在创建。但价值没有进入。没有例外。但是当我第二次尝试输入值时,会出现异常。



我该如何更正?如果有人需要查看更多的代码,我将发布。



这是用户输入数据的代码:

  addSubName = new TextField(); 
addSubName.setPromptText(Staff Name);
addSubName.setPrefSize(200,30);

final Button b2 = new Button(Add);
b2.setFont(Font.font(Calibri,FontWeight.BOLD,17));
b2.setPrefSize(70,30);
b2.setStyle(-fx-base:#0066ff;);
b2.setTextFill(Color.BLACK);
b2.setOnAction(new EventHandler< ActionEvent>(){
@Override
public void handle(ActionEvent e){

data.add(new Staff(addSubName .getText()));
addSubName.clear();

try {
enterStaff();
} catch(ClassNotFoundException ex){
Logger.getLogger(AddStaff.class.getName())。log(Level.SEVERE,null,ex);
} catch(SQLException ex){
Logger.getLogger(AddStaff.class.getName ).log(Level.SEVERE,null,ex);
}
}
});

异常详细信息是:

  com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:对于PRIMARY键,重复条目'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java: 45)
在java.lang.reflect.Constructor.newInstance(Constructor.java:526)
在com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com .mysql.jdbc.Util.getInstance(Util.java:386)
在com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1040)
在com.mysql.jdbc.MysqlIO.checkErrorPacket (MysqlIO.java:4120)
在com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at c om.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
在com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
在com.mysql.jdbc.ConnectionImpl。 execSQL(ConnectionImpl.java:2794)
在com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
在com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
在com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
在com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
在addstaff.AddStaff .enterStaff(AddStaff.java:149)
在addstaff.AddStaff $ 2.handle(AddStaff.java:100)
在addstaff.AddStaff $ 2.handle(AddStaff.java:92)
在com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:69)
在com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
在com.sun。 javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
在com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
在com。 com.sun.javafx上的
(.com) event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
在com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
在com.sun.javafx.event.EventUtil。 fireEvent(EventUtil.java:28)
在javafx.event.Event.fireEvent(Event.java:171)
在javafx.scene.Node.fireEvent(Node.java:6867)
在javafx.scene.control.Button.fire(Button.java:179)
在com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:193)
at com .sun.javafx.scene.control.skin.SkinBase $ 4.handle(SkinBase.java:336)
在com.sun.javafx.scen com.un.javafx.event.CompositeEventHandler.dispatchBubblingEvent com.unvent.EventHandlerManager.dispatchBubblingEvent .dispatchBubblingEvent(CompositeEventDispatcher.java:38)
在com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
在com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl .java:92)
在com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
在com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92 )
在com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
在com.sun.javafx.event.EventDispatchChainImpl.di spatchEvent(EventDispatchChainImpl.java:92)
在com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
在com.sun.javafx.event.EventUtil.fireEvent(EventUtil。 java:33)
在javafx.event.Event.fireEvent(Event.java:171)
在javafx.scene.Scene $ MouseHandler.process(Scene.java:3311)
在javafx .scene.Scene $ MouseHandler.process(Scene.java:3151)
在javafx.scene.Scene $ MouseHandler.access $ 1900(Scene.java:3106)
在javafx.scene.Scene.impl_processMouseEvent( Scene.java:1563)
在javafx.scene.Scene $ ScenePeerListener.mouseEvent(Scene.java:2248)
在com.sun.javafx.tk.quantum.GlassViewEventHandler $ MouseEventNotification.run(GlassViewEventHandler。 java:250)
在com.sun.javafx.tk.quantum.GlassViewEventHandler $ MouseEventNotification.run(GlassViewEventHandler.java:173)
在java.security.AccessController.doPrivileged(本机方法)
com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:292)
在com.sun.glass。 ui.View.handleMouseEvent(View.java:530)
在com.sun.glass.ui.View.notifyMouse(View.java:924)
在com.sun.glass.ui.win。 WinApplication._runLoop(Native Method)
在com.sun.glass.ui.win.WinApplication.access $ 100(WinApplication.java:17)
在com.sun.glass.ui.win.WinApplication $ 3 $ 1.run(WinApplication.java:67)
在java.lang.Thread.run(Thread.java:744)


解决方案

你shoud 删除 ; 在您的sql查询中:



错误查询:

  prepareStatement(create table staff(staffname varchar(30)primary key);); 

preparedStatement = connect.prepareStatement(insert into staff value(?););

正确的查询是:

  prepareStatement(create table staff(staffname varchar(30)primary key)); 

preparedStatement = connect.prepareStatement(insert into staff values(?));

检查您的插件查询



而且,我认为您的 INSERT 数据库中的值,该查询错误,提及 tablename 只有你不应该提到列名。所以你应该在你的查询中添加tablename。



错误的查询:

 插入员工价值(?)

正确查询:

  INSERT INTO table_name 
VALUES(value1,value2,value3,...);










更新:1



错误的代码:

  statement = connect.createStatement(); 
preparedStatement = connect
.prepareStatement(SELECT count(*)FROM information_schema.tables\\\

+WHERE table_schema ='project'AND table_name ='staff');
rs = preparedStatement.executeQuery();
rs.next();

您应该更改为:样本 / p>

  Class.forName(driverName).newInstance(); 
con = DriverManager.getConnection(connectionUrl + dbName,user,password);
st = con.createStatement();
String sql =SELECT * FROM employees;
rs = st.executeQuery(sql);

注意:


  1. 你不应该调用sql查询。

  2. 而您正在使用准备声明来电,你应该要到语句

  3. code> preparedStatement 无法解决。

  string sql = .... sql query ...; 
statement.executeQuery(sql)

更新:2: - >样本

  public class User 
{
private String empname ;
public String getEmpName()
{
return empname;
}
public void setEmpName(String empname)
{
this.empname = empname;
}






  public void addUser(User user)
{
try
{
PreparedStatement ps;
ps = connection.prepareStatement(INSERT INTO employee(empname,empaddress,depname)VALUES(?,?,?));
ps.setString(1,user.getEmpName());
ps.setString(2,user.getEmpAddress());
ps.setString(3,user.getDepName());
ps.executeUpdate();
}
catch(异常e)
{
System.out.println(e);
}
}


I am getting this exception from today onwards. Yesterday things were fine. I will post my code :

public void enterStaff() throws ClassNotFoundException, SQLException {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        connect = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/project?"
                        + "user=root&password=virus");
        statement = connect.createStatement();

        preparedStatement = connect
                .prepareStatement("SELECT count(*)FROM information_schema.tables\n"
                        + "WHERE table_schema = 'project' AND table_name = 'staff'");
        rs = preparedStatement.executeQuery();
        rs.next();
        int chk = rs.getInt(1);

        if (chk != 1) {
            preparedStatement = connect
                    .prepareStatement("create table staff (staffname varchar(30) primary key);");
            preparedStatement.executeUpdate();
        }

        preparedStatement = connect
                .prepareStatement("insert into staff values(?);");
        preparedStatement.setString(1, addSubName.getText());

        preparedStatement.executeUpdate();
    } catch (ClassNotFoundException | SQLException e) {
        throw e;
    } finally {
        close2();
    }

}

private void close2() {
    try {

        if (statement != null) {
            statement.close();
        }

        if (connect != null) {
            connect.close();
        }
    } catch (SQLException e) {

    }
}

I am trying to create a table with only one column and that column is the primary key. When the code is run for the first time the table is getting created. But value is not getting entered. No exception is shown then. But when I try to enter value for the second time, the exception comes up.

How can I correct this ? If anyone needs to see some more code I will post it.

This is the code through which the user enters the data :

    addSubName = new TextField();
    addSubName.setPromptText("Staff Name");
    addSubName.setPrefSize(200, 30);

    final Button b2 = new Button("Add");
    b2.setFont(Font.font("Calibri", FontWeight.BOLD, 17));
    b2.setPrefSize(70, 30);
    b2.setStyle(" -fx-base: #0066ff;");
    b2.setTextFill(Color.BLACK);
    b2.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {

            data.add(new Staff(addSubName.getText()));
            addSubName.clear();

            try {
                enterStaff();
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(AddStaff.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(AddStaff.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

The exception details is :

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1040)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at addstaff.AddStaff.enterStaff(AddStaff.java:149)
at addstaff.AddStaff$2.handle(AddStaff.java:100)
at addstaff.AddStaff$2.handle(AddStaff.java:92)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:69)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:28)
at javafx.event.Event.fireEvent(Event.java:171)
at javafx.scene.Node.fireEvent(Node.java:6867)
at javafx.scene.control.Button.fire(Button.java:179)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:193)
at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:336)
at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:329)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:64)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:33)
at javafx.event.Event.fireEvent(Event.java:171)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3311)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3151)
at javafx.scene.Scene$MouseHandler.access$1900(Scene.java:3106)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1563)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2248)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:250)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:173)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:292)
at com.sun.glass.ui.View.handleMouseEvent(View.java:530)
at com.sun.glass.ui.View.notifyMouse(View.java:924)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
at java.lang.Thread.run(Thread.java:744)
解决方案

you shoud remove the ; in your sql query:

wrong query:

prepareStatement("create table staff (staffname varchar(30) primary key);");

preparedStatement = connect.prepareStatement("insert into staff values(?);");

correct query is:

prepareStatement("create table staff (staffname varchar(30) primary key)");

preparedStatement = connect.prepareStatement("insert into staff values(?)");

CHECK YOUR INSERT QUERY

And, I think your INSERT the values in the db, that query is too wrong, did mention the tablename only, you should not mention the columnname. so you should must add the tablename with your query.

wrong query:

insert into staff values(?)

correct query:

    INSERT INTO table_name
    VALUES (value1,value2,value3,...);


refer this link:

http://www.w3schools.com/sql/sql_insert.asp

UPDATE:1

wrong code:

statement = connect.createStatement();
preparedStatement = connect
                .prepareStatement("SELECT count(*)FROM information_schema.tables\n"
                        + "WHERE table_schema = 'project' AND table_name = 'staff'");
        rs = preparedStatement.executeQuery();
        rs.next();

you should change like:sample

Class.forName(driverName).newInstance();
con=DriverManager.getConnection(connectionUrl+dbName,user,password);
st = con.createStatement();
String sql="SELECT * FROM employees";
rs=st.executeQuery(sql);

Note:

  1. you should not call the sql query.
  2. And, you are using preparedStatement to call, you should must chage to statement
  3. the preparedStatement is can't resolved.

like,

string sql=....sql query...;
statement.executeQuery(sql)

update:2:-->sample

public class User
{
private String empname;
public String getEmpName()
{
    return empname;
}
public void setEmpName(String empname)
{
    this.empname=empname;
}


public void addUser(User user)
{
    try
    {
        PreparedStatement ps;
        ps=connection.prepareStatement("INSERT INTO employee (empname,empaddress,depname) VALUES (?,?,?)");
        ps.setString(1, user.getEmpName());
        ps.setString(2, user.getEmpAddress());
        ps.setString(3, user.getDepName());
        ps.executeUpdate();
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}

这篇关于com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:键“PRIMARY”的重复条目“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:35