您的位置:首页 > 数据库 > MySQL

JDBC工具类及用法

2017-07-05 21:39 316 查看
1、配置数据库配置文件

在src目录下新建jdbc.properties文件,已键值对的形式编写数据库配置信息。

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day07
user=root
password=1234


2、封装JDBC工具类

package top.littlerich.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

public class JdbcUtils {
static final String DRIVERCLASS;
static final String URL;
static final String USER;
static final String PASSWORD;

static {
// 获取ResourceBundle ctrl+2 l
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");

// 获取指定的内容
DRIVERCLASS = bundle.getString("driverClass");
URL = bundle.getString("url");
USER = bundle.getString("user");
PASSWORD = bundle.getString("password");
}

static {
try {
Class.forName(DRIVERCLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

// 获取连接
public static Connection getConnection() throws SQLException {
return  DriverManager.getConnection(URL, USER, PASSWORD);
}

/**
* 释放资源
*
* @param conn
*            连接
* @param st
*            语句执行者
* @param rs
*            结果集
*/
public static void closeResource(Connection conn, Statement st, ResultSet rs) {
closeResultSet(rs);
closeStatement(st);
closeConn(conn);
}

/**
* 释放连接
*
* @param conn
*            连接
*/
public static void closeConn(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}

}

/**
* 释放语句执行者
*
* @param st
*            语句执行者
*/
public static void closeStatement(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
}

}

/**
* 释放结果集
*
* @param rs
*            结果集
*/
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}

}
}


3、使用JDBC工具类连接数据库并进行CURD操作,用法示例:

//存放配置文件
Properties prop = new Properties();
prop.load(new FileInputStream("src/dbcp.properties"));
//设置
//prop.setProperty("driverClassName", "com.mysql.jdbc.Driver");

//创建连接池
DataSource ds = new BasicDataSourceFactory().createDataSource(prop);

Connection conn=ds.getConnection();
String sql="insert into category values(?,?);";
PreparedStatement st=conn.prepareStatement(sql);

//设置参数
st.setString(1, "c012");
st.setString(2, "饮料1");

int i = st.executeUpdate();
System.out.println(i);
JdbcUtils.closeResource(conn, st, null);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql jdbc 数据库