我正在尝试从eclipse连接到mysql。首先,我在mysql中创建了表,然后我构建了mysql-connector-java-5.1.38.bin.jar的路径。我想向mysql插入一些数据,但是我得到了这个错误,我做错了什么?
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","root","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 :(得分:2)
MySQL Connector documentation对连接字符串的语法非常清楚:
jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] [?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
您尚未指定数据库名称,因此驱动程序不知道指向预准备语句的数据库。