第一种方式 直接获取驱动,地址,用户名,密码 并返回连接对象
package cn.tao.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
private JDBCUtils(){}
private static Connection con;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
//2获得连接 对象
String url ="jdbc:mysql://localhost:3306/day37";
String username="root";
String password="root";
con = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
throw new RuntimeException("数据库连接失败");
}
}
//定义静态方法 返回数据库的连接
public static Connection getConnection(){
return con;
}
//关资源
public static void close(Connection con, Statement stat){
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void close(Connection con, Statement stat,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
第二种方式 通过读取配置文件获得驱动,地址,用户,密码 定义方法返回连接对象
package cn.tao.demo;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class JDBCUtilsConfig {
private static Connection con;
private static String driverClass;
private static String url;
private static String user;
private static String password;
static{
try {
readConfig();
Class.forName(driverClass);
con = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readConfig() throws Exception{
InputStream in = JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties");
Properties pro = new Properties();
pro.load(in);
driverClass = pro.getProperty("driverClass");
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
}
public static Connection getConnection(){
return con;
}
}
第三种 连接池的方式
package cn.com.demo;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
public class JDBCUtils {
private static BasicDataSource data = new BasicDataSource();
static{
data.setDriverClassName("com.mysql.jdbc.Driver");
data.setUrl("jdbc:mysql://localhost:3306/day37");
data.setUsername("root");
data.setPassword("root");
data.setInitialSize(20);
data.setMaxActive(30);
data.setMaxIdle(5);
data.setMinIdle(1);
}
public static DataSource getDataSource(){
return data;
}