我已将mysql-connector-java-5.1.16-bin.jar
包含到我的Eclipse库中,此代码基于我在Web上找到的教程,因为我以前没有在Java中使用MySQL。不幸的是,我没有看到我在哪里使用acutual mysql-connector-java-5.1.16-bin.jar
,控制台打印Could not find driver.
意味着抛出了ClassNotFoundException
。你看到我看不到的(可能很明显的)问题吗?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.sql.Timestamp;
public class MysqlConnector {
private static MysqlConnector instance = null;
private static Connection conn = null;
private static String dbHost = "localhost";
private static String dbPort = "3306";
private static String database = "sample";
private static String dbUser = "root";
private static String dbPassword = "";
public MysqlConnector() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":"
+ dbPort + "/" + database + "?" + "user=" + dbUser + "&"
+ "password=" + dbPassword);
} catch (ClassNotFoundException e) {
System.out.println("Could not find driver."); //TODO LOGGER
} catch (SQLException e) {
System.out.println("Could not connect to database."); //TODO LOGGER
}
}
public static MysqlConnector getInstance()
{
if(instance == null)
instance = new MysqlConnector();
return instance;
}
public boolean validateApiKey(String apikey)
{
if(conn != null)
{
Statement query;
try {
query = conn.createStatement();
String sql = "SELECT startdate, expiration, active " + "FROM apikeys "
+ "WHERE apikey = '" + apikey +"'";
ResultSet result = query.executeQuery(sql);
if(result.getFetchSize()>0 && result.getInt("active")==1){
Date now = new Date();
Date startdate = result.getDate("startdate");
Date expirationdate = result.getDate("expiration");
if(now.before(expirationdate) && now.after(startdate)){
return true;
} else {
return false;
}
} else {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
return false;
}
}
答案 0 :(得分:2)
Right click your project > Build Path > Add libraries
并添加jar文件。
还要确保它位于运行时路径上。 Right click the main class > run as > run configurations > Classpath
答案 1 :(得分:0)
我唯一看到的是你需要在项目中添加MySQL Connector的库,而不仅仅是在你的Eclipse库中。
答案 2 :(得分:0)
你怎么运行这个?
当你做
时,你从那个jar中实例化一个类Class.forName("com.mysql.jdbc.Driver")
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#forName%28java.lang.String%29