数据库连接问题
DBSource.java文件:import java.sql.Connection;
import java.sql.SQLException;
public interface DBSource {
public Connection getConnection() throws SQLException;
public void closeConnection(Connection conn) throws SQLException;
}
SimpleDBSource.java文件:
import
import
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class SimpleDBSource implements DBSource {
private Properties props;
private String url;
private String user;
private String password;
public SimpleDBSource() throws IOException, ClassNotFoundException {
this("C:/Users/Administrator/Desktop/src/JDBC入门/简单的Connection工具类/jdbc.properties");
}
public SimpleDBSource(String configFile) throws IOException, ClassNotFoundException {
props = new Properties();
// Properties() ;
props.load(new FileInputStream(configFile));
// void load(InputStream inStream)
// 从输入流中读取属性列表(键和元素对)。
url = props.getProperty("onlyfun.caterpillar.url");
user = props.getProperty("onlyfun.caterpillar.user");
password = props.getProperty("onlyfun.caterpillar.password");
Class.forName(props.getProperty("onlyfun.caterpillar.driver"));
}
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public void closeConnection(Connection conn) throws SQLException {
conn.close();
}
}
Connection.java文件:
import
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionDemo {
public static void main(String[] args) {
try {
DBSource dbsource = new SimpleDBSource();
Connection conn = dbsource.getConnection();
if(!conn.isClosed()) {
System.out.println("数据库连接已开启……");
}
dbsource.closeConnection(conn);
if(conn.isClosed()) {
System.out.println("数据库连接已关闭……");
}
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e ) {
e.printStackTrace();
}
catch(SQLException e ) {
e.printStackTrace();
}
}
}
C:\Users\Administrator\Desktop\classes>java ConnectionDemo
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at (URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at (URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:171)
at SimpleDBSource.<init>(SimpleDBSource.java:39)
at SimpleDBSource.<init>(SimpleDBSource.java:17)
at ConnectionDemo.main(ConnectionDemo.java:11)
编译时老是出现上面的错误,不知道为什么,我已经将jar包导入了Classpath的环境变量中去了,求知道!!