com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown database 'db_library;'

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown database 'db_library;'相关的知识,希望对你有一定的参考价值。

eclipse老是报出这个错误,我有这个数据库,也有mysql-connector-java,也已经导入了这个包,可就是不行,请高手指教
数据库对的,没有错

参考技术A 看看MyEclipse你建的那个工程,config.properties里的设置,它是用来与数据库连接,看看数据库名对不对,密码用户什么的,再看看语句写的对不对 参考技术B 错误是说,找不到这个数据库'db_library;' 参考技术C 连数据库时,这句话String url = "jdbc:mysql://localhost/数据库名";数据库名可能和你建的数据库名不一样 参考技术D 是不是最后那个“;”的问题啊?追问

不是

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:重复条目 '' 键 'PRIMARY'

【中文标题】com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:重复条目 \'\' 键 \'PRIMARY\'【英文标题】:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '' for key 'PRIMARY'com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:重复条目 '' 键 'PRIMARY' 【发布时间】:2014-05-20 12:32:30 【问题描述】:

从今天开始,我将收到此异常。昨天一切都很好。我将发布我的代码:

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) 

    

我正在尝试创建一个只有一列的表,并且该列是主键。当代码第一次运行时,表被创建。但是没有输入价值。然后没有显示异常。但是当我第二次尝试输入值时,出现了异常。

我该如何纠正这个问题?如果有人需要查看更多代码,我会发布它。

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

    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: 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)

【问题讨论】:

我们能看到您插入的值吗?您的 create 语句没有 auto_increment 或任何类似的内容,因此可能插入值搞砸了。 @d_ominic 我应该发布什么? 一些示例插入值,或生成/确定您在插入语句中放入的值的代码。 您尝试通过文本框提交的值必须已经存在于表格中。您可能不止一次点击了Add 按钮。 不,我只按了一次按钮。我确信这一点。 【参考方案1】:

你应该在你的 sql 查询中使用 remove ;

查询错误:

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

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

正确的查询是:

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

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

检查您的插入查询

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

查询错误:

insert into staff values(?)

正确查询:

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

参考此链接:

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

更新:1

代码错误:

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

你应该改变如下:sample

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

注意:

    你不应该调用 sql 查询。 而且,你用preparedStatement打电话,你必须改成statement 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(Exception e)
    
        System.out.println(e);
    

【讨论】:

@Tom,检查这个答案 它不起作用。你注意到异常了吗?它说主键的重复值。例外是在第二次进入时出现,而不是第一次出现。这意味着数据没有输入到数据库中。为什么数据没有进入数据库? 在'b2.setOnAction(new EventHandler()'中我首先写了'addSubName.clear();'。然后我写了'enterStaff()'方法。所以自动它在插入到数据库中的表时会得到一个空值。所以我先调用了“enterStaff()”方法,然后调用了“addSubName.clear()”方法。但这也不起作用。 我怎样才能改变这个-preparedStatement.setString(1, msg); 该问题的哪一部分对我有帮助?【参考方案2】:

此错误的一个可能原因是您尝试在归档到表中的主键上输入相同的值。

例如,如果您有一个主键为 user_id 的表 users,并且您尝试输入以下内容:

INSERT INTO users ('user_id', 'name', 'age') VALUES (112233, 'Tom', 18);
INSERT INTO users ('user_id', 'name', 'age') VALUES (112233, 'Barry', 21);

会出现MySQLIntegrityConstraintViolationException: Duplicate entry 错误。

注意:在某些有效情况下,可能需要在 a 表中插入或更新列,在这种情况下,可以使用 ON DUPLICATE KEY UPDATE

例子:

INSERT INTO social_link ('user_id', 'social_id') VALUES (112233, 59874) ON DUPLICATE KEY UPDATE social_id=575123;

【讨论】:

以上是关于com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown database 'db_library;'的主要内容,如果未能解决你的问题,请参考以下文章

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:重复条目 '' 键 'PRIMARY'

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链路故障?

错误 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:表不存在

使用 JDBC 访问远程 MySQL 数据库时出现 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链路故障