[java]代码库
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
//java 连接MySql的三种方法
public class ConnectionUtil {
//第一种方法
public Connection getConnection(){
Connection conn = null;
try {
//Class.forName加载驱动
Class.forName("com.mysql.jdbc.Driver");
//DriverManager获得连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_db","root","mysqladmin");
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//第二种方法
public Connection getConnection(String driver,String url,String user,String password){
Connection conn = null;
try {
//Class.forName加载驱动
Class.forName(driver);
//DriverManager获得连接
conn = DriverManager.getConnection(url,user,password);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//第三种方法
public Connection openConnection(){
String driver = "";
String url = "";
String user = "";
String password = "";
Properties prop = new Properties();
Connection conn = null;
try {
//加载属性文件
prop.load(this.getClass().getClassLoader().getResourceAsStream("DBConfig.properties"));
driver = prop.getProperty("driver");
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
//Class.forName加载驱动
Class.forName(driver);
//DriverManager获得连接
conn = DriverManager.getConnection(url,user,password);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
初级程序员
by: 追梦不息 发表于:2017-11-08 16:48:19 顶(0) | 踩(0) 回复
刚好用到,去试试
回复评论