用的MYSQL版本是3.23.52,
驱动装的是mysql-connector-java-3.0.2-beta-bin.jar。
连接应该是没有问题的,因为用INSERT可以写入数据库。
但用 String queryString = " SELECT ID,Name FROM test"却不能检索数据表。
具体代码如下:
public class JDBCTest {
private static final String DRIVER_NAME = "org.gjt.mm.mysql.Driver";
private static final String DB_URL="jdbc:mysql://localhost/kelvin?user=root&password=666666";
private static final String QUERY= "SELECT ID,Name FROM test";
private static final String insertSql= "insert into test values(133,'aaa')";
public static void main(String[] args) {
try {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException ex) {ex.printStackTrace();
}
Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = conn.createStatement();
stmt.execute(insertSql);
ResultSet rslt = stmt.executeQuery(QUERY);
while (rslt.next() ) {
String name = rslt.getString("Name");
int id = rslt.getInt("ID");
System.out.println(id+"1111 " +name);
}
rslt.close();
stmt.close();
conn.close();
System.out.println("Success ! Connected to database");
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
}
运行报错:
java.sql.SQLException: Column 'Name' not found.
at com.mysql.jdbc.ResultSet.findColumn(ResultSet.java:2862)
at com.mysql.jdbc.ResultSet.getString(ResultSet.java:1990)
at com.kelvin.security.installtest.JDBCTest.main(JDBCTest.java:50)
若是用 (50) String name = rslt.getString(2);
(51) int id = rslt.getInt(1);
则出现:
java.sql.SQLException: Invalid value for getInt() - 'qpp'
at com.mysql.jdbc.ResultSet.getInt(ResultSet.java:1323)
at com.kelvin.security.installtest.JDBCTest.main(JDBCTest.java:51)
我很奇怪为什么写数据库可以,而读却不行?insertSql= "insert into test values(133,'aaa')"这条语句可以执行。select时也检索到了记录条数,但我就是得不到响应的列。