我在EC2 linux实例上,我似乎无法获取这个java代码来查询数据库,我在下面的代码底部显示错误。它表示它无法找到驱动程序,因为我知道我手动安装了mysql-connector-java-5.1.12.jar,因为当我安装Java时它不存在。我不知道如何检查jar是否正确安装?
import java.sql.*;
public class Java2MySql{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "myBlog";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "NoWay!";
Connection conn = null;
try {
Class.forName(driver);
}catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
}
System.out.println("MySQL JDBC Driver Registered!");
try{
conn = DriverManager.getConnection(url+dbName,userName,password);
//query users
Java2MySql j = new Java2MySql();
j.getUsers(conn);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
} finally {
try {
conn.close();
} catch (Throwable ignore){}
}
}
private void getUsers(Connection conn){
Statement stmt = null;
ResultSet rs = null;
try{
stmt = conn.createStatement() ;
String query = "select * from users ;" ;
s = stmt.executeQuery(query) ;
while ( rs.next() ) {
int numColumns = rs.getMetaData().getColumnCount();
for ( int i = 1 ; i <= numColumns ; i++ ) {
System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
}
}
}catch(SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
}finally {
try {
rs.close();
} catch (SQLException sqlEx) {}
try{
stmt.close();
} catch(SQLException sqlEx){}
}
}
}
例外:
$java Java2MySql
Where is your MySQL JDBC Driver?
MySQL JDBC Driver Registered!
Connection Failed! Check output console
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/myBlog
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at Java2MySql.main(Java2MySql.java:22)
答案 0 :(得分:0)
有问题的JAR需要在您的CLASSPATH中。在调用java
或设置CLASSPATH环境变量时,您可能希望在尝试使用-classpath参数运行的Java应用程序之前显式设置其位置。
答案 1 :(得分:0)
首先,为什么不在url本身中指定数据库。
其次删除位于双引号内的查询末尾的分号。
第三件事是制造
rs=stmt.executeQuery(query);
最后在你的类路径中有mysql-connector.jar。