今天从开始写了一个jdbc连接mysql驱动的程序
真的是各种报错啊
首先这是代码
package com.dmeck; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class Jdbcbase { public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mytest";
String user="root";
String pass="mysql" ;
String className="com.mysql.jdbc.Driver";
try{
Class.forName(className);
}catch(Exception e) {
System.out.print("Error loading Mysql Driver!");
e.printStackTrace();
}
Connection connection;
try { connection = DriverManager.getConnection(url, user, pass);
Statement createStatement = connection.createStatement(); ResultSet query = createStatement.executeQuery("select * from user");
while(query.next()) {
System.out.println(query.getString("user"));
}
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}
嗯,先说下问题
项目运行时会出现
Error loading Mysql Driver!java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.dmeck.Jdbcbase.main(Jdbcbase.java:17)
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mytest
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.dmeck.Jdbcbase.main(Jdbcbase.java:25)
首先这个错误我无法复现,因为我的项目是maven管理的
jdbc驱动是5.1.6
这个错误是因为maven网络不好而引起的jar包出现错误,只要eclispe加载jar的字节文件不是下列现象就说明你的jar包有问题