2016-03-12 52 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_。您在錯誤的地方給了數據庫名稱。 –