我无法解决为什么java无法看到我的mysql驱动程序:
但我仍然得到ClassNotFound Exceptions。还有什么我需要做的吗?
类示例:
package org.rcz.dbtest;
import java.sql.*;
public class DB {
private Connection connect = null;
private Statement stmt = null;
private PreparedStatement prepared = null;
private ResultSet rset = null;
private String driverClassName = "com.myqsl.jdbc.Driver";
private String jdbcUrl = "jdbc:mysql://localhost/ctic_local?user=root&password=server";
private String queryString;
public DB(String query)
{
System.out.println(System.getProperty("java.class.path"));
queryString = query;
}
public void readFromDatabase()
{
try
{
Class.forName(driverClassName);
connect = DriverManager.getConnection(jdbcUrl);
stmt = connect.createStatement();
rset = stmt.executeQuery(queryString);
writeResultSet(rset);
}
catch (ClassNotFoundException cex)
{
System.out.println("Could not find mysql class");
}
catch(SQLException sqex)
{
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("name");
String comment = resultSet.getString("comment");
System.out.println("User: " + user);
System.out.println("Comment: " + comment);
}
}
}
我的主要类只是将查询传递到DB类:
package org.rcz.dbtest;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException
{
String qstring = "SELECT * FROM comments";
new DB(qstring).readFromDatabase();
System.in.read();
}
}
答案 0 :(得分:3)
您在驱动程序类名称中输入了错字。
private String driverClassName = "com.myqsl.jdbc.Driver";
应该是
private String driverClassName = "com.mysql.jdbc.Driver";
// -------------------------------------^
无关,将Connection
,Statement
和ResultSet
等数据库资源作为类的实例变量是一个坏主意。您需要在try-finally
块中尽可能短的时间内创建,使用和关闭它们,以防止资源泄漏。另请参阅此问题/答案:When my app loses connection, how should I recover it?