2016-03-12 53 views
1

我想从eclipse连接到mysql。首先,我在mysql中创建表,然后我建立了mysql-connector-java-5.1.38.bin.jar的路径。我想插入一些数据到MySQL,但我得到这个错误我做错了什么?在eclipse中没有从mysql中选择数据库java

MYSQL

Create database readers; 
Use readers; 

CREATE TABLE reader 
(
Name varchar(265), 
Surname varchar(255), 
City varchar(255), 
Capital varchar(255) 
); 

我在这里的Java代码

Class.forName("com.mysql.jdbc.Driver"); 

      //Connect to DB server 
      Connection connection = 
        DriverManager.getConnection(jdbc:mysql://localhost:3306/?readers=true","ro‌​ot","password"); 

      System.out.println("Connected to MySQL"); 

      //Create Prepared Statement 
      PreparedStatement statement = 
        connection.prepareStatement("insert into readers (Name,Surname,City,Capital) values(?,?,?,?)"); 

错误

Connected to MySQL 
java.sql.SQLException: No database selected 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814) 
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478) 
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625) 
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2551) 
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861) 
    at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1192) 
    at edu.sabanciuniv.ReadWriteThread.run(ReadWriteThread.java:57) 

我找遍每一个问题在这里,但没有找到我的问题的任何解决方案。它不重复,那个问题的答案不是我的解决方案。我写了我的数据库名称,它是getConnection部分的“读者”。

+0

也许不是原因,但是你的SQL语句有错误。它提到了数据库“读者”的名字,而不是你的表名“读者”。 – trincot

回答

2

MySQL Connector documentation是在连接字符串的语法很清楚:

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] [?propertyName1=propertyValue1[&propertyName2=propertyValue2]...] 

您还没有指定的数据库名称,因此司机不知道直接准备好的声明,数据库。

+0

例如,我确实\t \t \t \t \t DriverManager.getConnection(“jdbc:mysql:// localhost:3306 /?readers = true”,“root”,“password”);我的数据库名称是我现在指定的读者,但没有任何变化。 @ jim-garrison –

+1

阅读连接字符串语法_carefully_。您在错误的地方给了数据库名称。 –