JDBC工具类的编写,使用以及配置文件(详细)
JDBC工具类的编写
public class JDBCUtils{
private static final String driverClassName;
private static final String url;
private static final String username;
private static final String password;
static{ //更改信息在这里改即可。static代码块也可以另外写成配置文件
driverClassName="com.mysql.jdbc.Driver";
url="jdbc:mysql:///dbe"; //数据库名称是dbe
username="root"; //用户名:root
password="root"; //密码: root
}
//加载驱动的方法
public static void loadDriver(){
try{
Class.forName(driverClassName);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
//获取连接的方法
public static Connection getConnection(){
Connection conn = null;
try{
loadDriver(); //将驱动一并注册
conn=DriverManager.getConnection(url,username,password);
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
//释放资源的方法
public static void release(Statement stmt,Connection conn){
if(stmt != null) {
try {
stmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
} //增删改释放资源
public static void release(ResultSet rs,Statement stmt,Connection conn){
if(rs !=null){
try{
rs.close();
}catch(SQLException e){
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
} //查询...释放资源
}
JDBC工具类的使用
public class Jdbcdemo{
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = JDBCUtils.getConnection(); //获得连接
stmt = conn.createStatement(); //创建执行sql语句的对象
String sql = "select * from user"; //查询user表的所有信息
rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt("id")+" "+rs.getString("username")+" "+rs.getString("password"));
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtils.release(rs,stmt,conn);
}
}
}
Tip:将static代码块改成配置文件以获取配置信息
在项目的src文件夹下创建配置文件db.properties.
在里面输入配置信息,以键值对的形式:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///dbe
username=root
password=root
接下来在工具类中解析配置文件,获取到具体内容,为常量赋值
static{
Properties p = new Properties();
try{
p.load(new FileInputStream("src/db.properties"));
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
driverClassName=p.getProperty("driverClassName");
url=p.getProperty("url");
username=p.getProperty("username");
password=p.getProperty("password");
}