[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: 云代码会员 发表于:2015-01-20 20:02:44 顶(0) | 踩(0) 回复
收藏、省着忘了还得找、
回复评论