java 连接mysql数据库
2017-10-10 本文已影响0人
小小白园
需要导入驱动包,我的版本是:mysql-connector-java-5.1.44-bin.jar
导入到WEB-INF下面的lib文件夹下,还需Bulid Path一下。
import java.sql.Connection;
import java.sql.DriverManager;
public class fzConn {
private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://localhost:8806/表名";
private static String name="root";
private static String password="你的密码";
private static Connection conn;
// 加载驱动
static{
try {
Class.forName(DRIVER_CLASS);
} catch (Exception e) {
System.out.println("加载驱动错误");
System.out.println(e.getMessage());
}
}
// 取得连接
public static Connection getConnection(){
try {
conn = DriverManager.getConnection(url, name, password);
System.out.println("连接成功");
} catch (Exception e) {
System.out.println("取得连接错误");
System.out.println(e.getMessage());
}
return conn;
}
}