您的位置:首页 > 数据库

使用配置文件和工具类连接数据库

2018-04-01 20:20 609 查看
使用配置文件加工具类的方式连接数据库不仅简化了操作更有利于后期的维护(如果需要更改数据库的话)

properties配置文件:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8
username=root
password=123456建议将properties文件放在src文件夹下




另外,要注意配置文件写的格式,每条语句后面不能有空格,否则会报错!类似这样的错误




JDBCUtils文件:public class JDBCUtils {
//声明静态变量
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;

//读取properties文件中的数据
static{
try {
//1.通过当前类获取类加载器
ClassLoader cl = JDBCUtils.class.getClassLoader();
//2.通过类加载器的方法获取一个输入流
InputStream is = cl.getResourceAsStream("db.properties");
//3.创建一个properties对象
Properties p = new Properties();
//4.加载输入流
p.load(is);
//5.获取配置文件中的数据
driver = p.getProperty("driver");
url = p.getProperty("url");
username = p.getProperty("username");
password = p.getProperty("password");

} catch (IOException e) {
e.printStackTrace();
}

}
//获取数据库连接
public static Connection getConnection(){
Connection con = null;
try {
//加载驱动
Class.forName(driver);
//创建连接
con = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
//释放连接
public static void CloseConnection(Connection con,PreparedStatement pstmt,ResultSet res){
try{
if(con!=null){
con.close();
}
if(pstmt!=null){
pstmt.close();
}
if(res!=null){
res.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}

}
测试类JDBCTest文件:public class JDBCTest {

@Test
public void TestJDBC(){
try {
Connection con = JDBCUtils.getConnection();
String sql = "insert into sc values(?,?,null)";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, "啦啦啦");
pstmt.setInt(2, 5);
int res = pstmt.executeUpdate();
if(res>0){
System.out.println("插入成功");
}else{
System.out.println("插入失败");
}

} catch (SQLException e) {
e.printStackTrace();
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: