当然最好是mysql版本对应相应的驱动,但高版本的驱动一般都能兼容低版本的。首先得保证有驱动,数据库连接权限,驱动要放进自己的程序里,一般没什么问题,给你一个程序,也是刚才别人问我的,他的程序没有问题。
import java.sql.*;
public class Conn {
private static Connection con;
private Statement stmt;
private ResultSet rs;
private static final String drivername ="com.mysql.jdbc.Driver"; //"com.microsoft.jdbc.sqlserver.SQLServerDriver";
private static final String url ="jdbc:mysql://localhost:3306/test"; //"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=plane;user=sa;password=sqlserver;";
public static synchronized Connection getCon() throws Exception {
try {
Class.forName(drivername);
con = DriverManager.getConnection(url,"root","root");//写上自己的用户和密码
return con;
} catch (SQLException e) {
System.err.println(e.getMessage());
throw e;
}
}
public Statement getStmtread() {
try {
con = getCon();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
return stmt;
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
return null;
}
public ResultSet getRs(String sql) {
try {
stmt = getStmtread();
rs = stmt.executeQuery(sql);
return rs;
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
return null;
}
public Statement getStmt() {
try {
con = getCon();
stmt = con.createStatement();
return stmt;
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
return null;
}
public synchronized void close() {
try {
if (rs != null) {
rs.close();
rs = null;
}
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
try {
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
public static void main(String[]args) throws Exception {
Conn c = new Conn();
c.getCon();
ResultSet rs = c.getRs("select * from user");
while(rs!=null&&rs.next()) {
System.out.println(rs.getString("username"));
}
}
}
我传给你,我用是jdk1.7.0 mysql5.0 tomcat 6.0 myeclipse 6.0 百度hi随时在,需要me 我
连接mysql只需要一个jar包就可以了!!!
Connector/J 5.1 支持Mysql 4.1、Mysql 5.0、Mysql 5.1、Mysql 6.0 alpha这些版本。
Connector/J 5.0 支持MySQL 4.1、MySQL 5.0 servers、distributed transaction (XA)。
Connector/J 3.1 支持MySQL 4.1、MySQL 5.0 servers、MySQL 5.0 except distributed transaction (XA) support。
Connector/J 3.0 支持MySQL 3.x or MySQL 4.1。
向下兼容,选个高版本的就行。高版本的bug少