程序员打交道最多的还是数据库。一般我们会选择各种各样的框架,其对数据库的操作完全封装了,但是有些小 项目,小网站什么的用框架又太小题大作了,还有就是入门的程序员需要了解jdbc的过程。所以小编自己封装了这个jdbc,就当小框架用吧,第一次写,还请朋友们多指点。
废话不多说,上图。
1.采用数据库连接池的
使用数据库连接池的
package com.zhumeng.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
/**
* @author 刘鹏 功能:jdbc连接工具类
* jdbc的简单封装
* */
public class MyConnection {
private static Connection conn =
null
;
// 数据库连接
private static PreparedStatement ps =
null
;
// 预编译声明
private static ResultSet rs =
null
;
// 结果集
/**
* 获取数据库连接
*
* @return Connection
*/
public static Connection getConnection() {
try
{
Context c =
new
InitialContext();
DataSource ds = (DataSource)c.lookup(
"java:comp/env/jdbc/mysql"
);
conn = ds.getConnection();
// conn = DriverManager.getConnection(url, user, password);
}
catch
(Exception e) {
e.printStackTrace();
throw
new
RuntimeException(
"获取链接对象connection出现错误"
);
}
return
conn;
}
/**
* 获得预编译声明
* */
public static PreparedStatement getPreparedStatement(String sql) {
getConnection();
// conn实例化
try
{
ps = conn.prepareStatement(sql);
}
catch
(SQLException e) {
// e.printStackTrace();
throw
new
RuntimeException(
"获取预编译对象PreparedStatement出现错误"
);
}
return
ps;
}
/**
* 执行查找,单个或者多个查找都可以返回List<Map
>试用于网站
*
* @return List<Map
>
* */
// public static List<Map
> find(String sql, Object... obj) {
// // 定义一个list,用来存放resultset的数据,map即一result的某一行的数据,即存的一个对象
// List<Map
> list = new ArrayList<Map >();
// getPreparedStatement(sql);// 实例化预编译对象ps
// try {
// if (obj.length > 0) {// 如果obj有数据,即有传来的参数
// for (int i = 0; i < obj.length; i++) {// 循环把参数 赋给预编译的声明
// ps.setObject(i + 1, obj[i]);
// }
// }
// rs = ps.executeQuery();
// ResultSetMetaData metaDate = rs.getMetaData();// 获得结果集的元数据
// int colsNum = metaDate.getColumnCount();// 获取查询的列数
//
// while (rs.next()) {
// Map
map = new HashMap ();//
// 定义一个map用来存放结果集的某一行的数据
// for (int i = 0; i < colsNum; i++) {
// String colsName = metaDate.getColumnName(i + 1);// 获得列名
// Object colsValue = rs.getObject(colsName);// 获得列值
// if (colsValue == null) {// 如果或的列值为空,赋值为空字符串
// colsValue = "";
// }
// map.put(colsName, colsValue);// 保存为键值对
// }
// list.add(map);// 添加到list集合
// }
//
// } catch (Exception e) {
// // e.printStackTrace();
// throw new RuntimeException("查询时出现错误");
// } finally {
// closeAll();
// }
// return list;
// }
public static
List find(T javaBean, String sql, Object... obj) {
// 定义一个list,用来存放resultset的数据,map即一result的某一行的数据,即存的一个对象
List<Map
> mapList = new
ArrayList<Map
>();
getPreparedStatement(sql);
// 实例化预编译对象ps
try
{
if
(obj.length > 0) {
// 如果obj有数据,即有传来的参数
for
(int i = 0; i < obj.length; i++) {
// 循环把参数 赋给预编译的声明
ps.setObject(i + 1, obj[i]);
}
}
rs = ps.executeQuery();
ResultSetMetaData metaDate = rs.getMetaData();
// 获得结果集的元数据
int colsNum = metaDate.getColumnCount();
// 获取查询的列数
while
(rs.next()) {
Map
map = new
HashMap
(); // 定义一个map用来存放结果集的某一行的数据
for
(int i = 0; i < colsNum; i++) {
String colsName = metaDate.getColumnName(i + 1);
// 获得列名
Object colsValue = rs.getObject(colsName);
// 获得列值
// if (colsValue == null) {// 如果或的列值为空,赋值为空字符串
// colsValue = "";
// }
map.put(colsName, colsValue);
// 保存为键值对
}
mapList.add(map);
// 添加到list集合
}
}
catch
(Exception e) {
e.printStackTrace();
// throw new RuntimeException("查询时出现错误");
} finally {
closeAll();
}
List
list = MapUtils.map2Java(javaBean, mapList); // 获得查询的数据,并封装成对应的bean返回list集合
return
list;
}
/**
* 单个查询,传入什么类型的,返回什么类型。泛型bean
*
* @return T
* */
public static
T findOne(T javaBean, String sql, Object... obj) {
List
list = find(javaBean, sql, obj);
if
(list ==
null
|| list.size() == 0) {
// list为空返回null,除去空指针异常
return
null
;
}
else
{
return
list.get(0);
}
}
/**
* 查询总数据
* */
public static int dateCount(String sql){
ps=getPreparedStatement(sql);
int row=0;
try
{
rs = ps.executeQuery();
if
(rs.next()){
row= rs.getInt(1);
}
}
catch
(SQLException e) {
// e.printStackTrace();
throw
new
RuntimeException(
"查询总数据条数失败!"
);
}
return
row;
}
/**
* 查询,返回ResultSet结果集
*
* @return ResultSet
* */
// public static ResultSet findMany(String sql, Object... obj) {
// /*
// * 可变参数的特点:只能出现在参数列表的最后;
// * ...位于变量类型和变量名之间,前后有无空格都可以;调用可变参数的方法时,编译器为该可变参数隐含创建一个数组
// * ,在方法体中一数组的形式访问可变参数。
// */
// getPreparedStatement(sql);// 实例化预编译对象ps
// try {
// if (obj.length > 0) {
// for (int i = 0; i < obj.length; i++) {// 循环把参数 赋给预编译的声明
// ps.setObject(i + 1, obj[i]);
// }
// }
// rs = ps.executeQuery();// 获得查询结果
// } catch (Exception e) {
// // e.printStackTrace();
// throw new RuntimeException("查询时出现错误");
// } finally {
// closeAll();
// }
// return rs;
// }
/**
* update 执行修改数据
*
* @return int
* */
public static int update(String sql, Object... obj) {
int result = 0;
getPreparedStatement(sql);
// 实例化预编译对象ps
try
{
if
(obj.length > 0) {
for
(int i = 0; i < obj.length; i++) {
// 循环把参数 赋给预编译的声明
ps.setObject(i + 1, obj[i]);
}
}
result = ps.executeUpdate();
}
catch
(Exception e) {
// e.printStackTrace();
throw
new
RuntimeException(
"执行DML语句(增,删,改)时出现错误"
);
} finally {
closeAll();
}
return
result;
}
/**
* 关闭数据库连接
*/
public static void closeAll() {
try
{
if
(rs !=
null
) {
rs.close();
}
if
(ps !=
null
) {
ps.close();
}
if
(conn !=
null
) {
conn.close();
}
}
catch
(SQLException e) {
// e.printStackTrace();
throw
new
RuntimeException(
"关闭连接时出现错误"
);
}
}
}
为了操作方便,我封装了个map转bean的类
package com.zhumeng.util;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Map工具类
* 实习map跟object的转换
*/
public class MapUtils {
/**
* Map集合对象转化成 JavaBean集合对象
*
* @param javaBean JavaBean实例对象
* @param mapList Map数据集对象
* @return
*/
public static
List map2Java(T javaBean, List<Map > mapList) { if(mapList == null || mapList.isEmpty()){
return null;
}
List
objectList = new ArrayList (); T object = null;
for(Map
map : mapList){ if(map != null){
object = map2Java(javaBean, map);
objectList.add(object);
}
}
return objectList;
}
/**
* Map对象转化成 JavaBean对象
*
* @param javaBean JavaBean实例对象
* @param map Map对象
* @return
*/
@SuppressWarnings("unchecked")
public static
T map2Java(T javaBean, Map map) { try {
// 获取javaBean属性
BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClass());
// 创建 JavaBean 对象
Object obj = javaBean.getClass().newInstance();
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
if (propertyDescriptors != null && propertyDescriptors.length > 0) {
String propertyName = null; // javaBean属性名
Object propertyValue = null; // javaBean属性值
for (PropertyDescriptor pd : propertyDescriptors) {
propertyName = pd.getName();
if (map.containsKey(propertyName)) {
propertyValue = map.get(propertyName);
pd.getWriteMethod().invoke(obj, new Object[] { propertyValue });
}
}
return (T) obj;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* JavaBean对象转化成Map对象
*
* @param javaBean
* @return map
*
*/
// @SuppressWarnings({ "rawtypes", "unchecked" })
// public static Map java2Map(Object javaBean) {
// Map map = new HashMap();
//
// try {
// // 获取javaBean属性
// BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClass());
//
// PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
// if (propertyDescriptors != null && propertyDescriptors.length > 0) {
// String propertyName = null; // javaBean属性名
// Object propertyValue = null; // javaBean属性值
// for (PropertyDescriptor pd : propertyDescriptors) {
// propertyName = pd.getName();
// if (!propertyName.equals("class")) {
// Method readMethod = pd.getReadMethod();
// propertyValue = readMethod.invoke(javaBean, new Object[0]);
// map.put(propertyName, propertyValue);
// }
// }
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return map;
// }
//
}
2.从文件外读取参数的方式:
db.properties中的参数
/**
* @author 刘鹏 功能:jdbc连接工具类 1.获得连接connection对象(需要从properties文件读取连接信息)
* */
public class MyConnection {
private static String driver;// 驱动
private static String url;// 数据库url
private static String user;// 用户名
private static String password;// 密码
private static Connection conn = null;// 数据库连接
private static PreparedStatement ps = null;// 预编译声明
private static ResultSet rs = null;// 结果集
// 从properties文件读取链接信息
public static void getProperties() {
try (BufferedInputStream bi = new BufferedInputStream(
new FileInputStream("src/com/peng/util/db.properties"));) {
Properties pro = new Properties();
pro.load(bi);
driver = pro.getProperty("jdbc.driver").trim();
url = pro.getProperty("jdbc.url").trim();
user = pro.getProperty("jdbc.user").trim();
password = pro.getProperty("jdbc.password").trim();
} catch (Exception e) {
new RuntimeException("获得链接驱动信息出现错误");
}
}
// 类一装入内存是就加载数据库连接驱动
static {
getProperties();
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
new RuntimeException("加载驱动类出现错误");
}
}
/**
* 获取数据库连接
*
* @return Connection
*/
public static Connection getConnection() {
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// e.printStackTrace();
throw new RuntimeException("获取链接对象connection出现错误");
}
return conn;
}
/**
* 获得预编译声明
* */
public static PreparedStatement getPreparedStatement(String sql) {
getConnection();// conn实例化
try {
ps = conn.prepareStatement(sql);
} catch (SQLException e) {
// e.printStackTrace();
throw new RuntimeException("获取预编译对象PreparedStatement出现错误");
}
return ps;
}
剩下的方法同上边使用数据库连接池的。查询单个数据或者批量查找数据