1、建立db.properties文件url=jdbc:Mysql://localhost:3306/testdb user=root passWord=root driverClass=com.mysql
url=jdbc:Mysql://localhost:3306/testdb
user=root
passWord=root
driverClass=com.mysql.jdbc.Driver
package com.rk.db.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtil
{
private static final String url;
private static final String user;
private static final String password;
private static final String driverClass;
static
{
try
{
//读取db.properties文件
InputStream inStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties props = new Properties();
//加载文件
props.load(inStream);
//读取信息
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
driverClass = props.getProperty("driverClass");
//注册驱动程序
Class.forName(driverClass);
}
catch (IOException e)
{
System.out.println("读取数据库配置文件出错");
throw new RuntimeException(e);
}
catch (ClassNotFoundException e)
{
System.out.println("数据库驱程程序注册出错");
throw new RuntimeException(e);
}
}
public static Connection getConnection()
{
try
{
return DriverManager.getConnection(url,user,password);
}
catch (SQLException e)
{
System.out.println("获取数据库连接出错");
throw new RuntimeException(e);
}
}
public static void close(Connection conn,Statement stmt,ResultSet rs)
{
closeQuietly(rs);
closeQuietly(stmt);
closeQuietly(conn);
}
public static void closeQuietly(AutoCloseable ac)
{
if(ac != null)
{
try
{
ac.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
--结束END--
本文标题: JDBC系列:(2.5)创建JDBCUtils工具类
本文链接: https://www.lsjlt.com/news/38359.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-16
2024-05-16
2024-05-16
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0