package com.sunjing.palm;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.beanutils.BeanUtils;
public class DbUtil {
private static Map paramsMap = new HashMap();
private static final String classPackage = "com.ord.model."; //1.将对应数据库的JavaBean放到此包下面(如:UserInfo)
private static ConnectionPool connPool = new ConnectionPool();
/**
* 查询操作
* @param sql
* @param param
* @param className
* @return
*/
public static List query(String sql, Map param, String className) {
List result = new ArrayList();
try {
Connection conn = connPool.getConnection();
PreparedStatement p = conn.prepareStatement(parseSql(sql));
boolean flag = fillParameters(p, param);
if (flag) {
ResultSet rs = p.executeQuery();
result = buildResult(rs, className);
}
} catch (SQLException e) {
e.printStackTrace();
}
close();
return result;
}
/**
* 修改和删除操作
* @param sql
* @param param
* @return
*/
public static boolean update(String sql, Map param) {
try {
Connection conn = connPool.getConnection(); // 从连接库中获取一个可用的连接
PreparedStatement p = conn.prepareStatement(parseSql(sql));
boolean flag = fillParameters(p, param);
if (flag) {
if (p.executeUpdate() == 1) {
return true;
}else {
return false;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
close();
return false;
}
/**
* 关闭数据库
*/
private static void close(){
}
private static List buildResult(ResultSet rs, String className) {
List result = new ArrayList();
try {
Class c = Class.forName(classPackage + className);
Field[] fields = c.getDeclaredFields();
while (rs.next()) {
Object bean = c.newInstance();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
BeanUtils.setProperty(bean, field.getName(), rs.getObject(field.getName()));
}
result.add(bean);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return result;
}
/**
* 替换sql语句中的命名参数
* (select * from db where name=:name and age=:age
* 转换后为
* select * from db where name=? and age =?
* )
* @param sql
* @return
*/
public static String parseSql(String sql) {
String regex = "(:(//w+))";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(sql);
paramsMap.clear();
int idx = 1;
while (m.find()) {
//参数名称可能有重复,使用序号来做Key
paramsMap.put(new Integer(idx++), m.group(2));
}
String result = sql.replaceAll(regex, "?");
return result;
}
/**
* 填充PreparedStatement参数
* @param ps
* @param param
* @return
*/
private static boolean fillParameters(PreparedStatement ps, Map param) {
boolean result = true;
String paramName = null;
Object paramValue = null;
int idx = 1;
for (Iterator itr = paramsMap.entrySet().iterator(); itr.hasNext();) {
Entry entry = (Entry) itr.next();
paramName = (String) entry.getValue();
idx = ((Integer) entry.getKey()).intValue();
//不包含会返回null
paramValue = param.get(paramName);
try {
ps.setObject(idx, paramValue);
} catch (Exception e) {
result = false;
}
}
return result;
}
}
/**
*JavaBean
name对应数据库中字段name
age对应数据库字段age
*
*/
public class UserInof{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.sunjing.palm;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
public class BeanUtils {
/**
*
* @param bean 赋值的JavaBean
* @param name JavaBean的属性名
* @param value 属性的值Integer :20 Double :20d Float :20f Long:20L Boolean:true|false
*/
public static void setProperty(Object bean,String name,Object value){
Class beanClass = bean.getClass();
String methodName ="set"+ name.substring(0, 1).toUpperCase()+name.substring(1);
Class argClass = Object.class;
if (value instanceof Boolean) {
argClass = Boolean.class;
} else if (value instanceof String) {
argClass = String.class;
} else if (value instanceof Integer) {
argClass = Integer.class;
} else if (value instanceof Double) {
argClass = Double.class;
} else if (value instanceof Long) {
argClass = Long.class;
} else if (value instanceof Float) {
argClass = Float.class;
} else {
throw new RuntimeException(
"Not set for other types yet");
}
try {
Method method =beanClass.getMethod(methodName, argClass);
method.invoke(bean, value);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
public class DbUtilsTest(){
pulbic static void main(String args[]){
String sql = "select * from user where name=:name and age=:age";
Map param = new HashMap();
param.put("name","sj"); //2.Map中的关键字一定要和sql语句中命令参数一样 即:name中的name
param.put("age",23);
List result =DbUtils.query(sql,param,"UserInfo"); //3.一定要传对应表user的类,此处是UserInfo类。
for(int i=0;i<result.size();i++){
UserInfo userInfo = (UserInfo)result.get(i);
System.out.println(userInfo.getName()+"---"+useInfo.getAge());
}
}
}
分享到:
相关推荐
用Java简单的实现SqlServer的封装,麻雀虽小,五脏俱全,用类的方式封装使得解读Java数据库操作更为明确,其中包含了查询、执行sql等。
java JDBC 连接sql server封装
通过sql查询结果封装成json * * <p>Example: * <code>String sql = "select id,username,password,sex from user where id=?"; 预处理参数列表 * @return {"id":"1","username":"jibs","password":...
JAVA 连接sqlserver类 已封装好 & sqljdbc.jar 包含sqljdbc_4.jar 封装完整Sqlserver类
使用本地sql语句查询后,无需再使用Object对查询结果进行强制转换,而是直接将查询结果放到实体Bean里了。 PS: 其实只有一版,这里只所以叫最终版是因为该附件我上传了好几天传不上去,到最后报告说‘资源已经存在...
关于java对SQLite和sql的封装类,可以实现增删改,查,事务操作
工作分享:Java实现SQL动态封装工具,废话不多说,直接上代码
封装jdbc即是把对数据库的连接操作封装在一个类中, 外部使用无需在重新建立连接,只需写出要执行的sql语句,就可执行。 也无需关闭,所有的都封装在一个类中。
3.JAVA 定时器及SqlServer和Oracle封装链接数据库,增/删/改/查可直接使用(提供JAR) 4.从JDK的安装到最后定时器发布成功,都有非常详细的操作说明及截图,新手按照操作说明及截图,很快可以掌握原理,在此基础上...
java数据库连接的简单类,初学JDBC或编简单JSP或Servlet的人用得着
java连接各种数据库改版2012-01-18
经典java数据库封装类,package com.bjsxt.shopping.util; import java.sql.*; public class DB { public static Connection getConn() { Connection conn = null; try { Class.forName(...
hibernate将本地SQL查询结果封装成对象(最终).zip
只用于sqlserver数据库每张表的封装可以为C#和Java 两种选择
附SQLServer数据库的Java聊天室课程设计源码和文档,源代码完整,学习网络编程很不错的参考程序。界面像网页版 的聊天室,可对所有人发消息,聊天室的功能都基本具备了。源代码文件包括了:聊天系统登录程序、聊天...
5. Executor执行器要处理的SQL信息是封装到一个底层对象MappedStatement中 该对象包括SQL语句 输入参数映射信息 输出结果映射信息 其中输入参数和输出结果的映射类型包括HashMap集合对象 POJO对象类型
MyBatis 多条件查询及动态SQL 粉丝可见 ybb_ymm 已于 2023-02-02 11:09:17 修改 642 收藏 3 分类专栏: java 文章标签: mybatis sql mysql 编辑 版权 java 专栏收录该内容 104 篇文章2 订阅 背景 MyBatis是一...
整合了一套crud代码,减少sql查询,封装mysql和mongodb等操作 参数说明https://mp.csdn.net/mp_download/manage/download/UpDetailed
代码已封装为java函数,mysql和poi相关jar包请自行百度下载,只需要传入sql、path、fileName即可执行,调用示例: String path="E:\\\\\\\\\\\\\\\\111\\\\\\\\\\\\\\\\; String fileName="test"; String sql=...
通过jdbc的方式访问数据库: 1.程序是整理的韩顺平oracle教学视频中的一个例子。 2.假设本机安装了oracle...4.程序对数据库操作进行了一定程度的封装,封装函数放在SQLHelper类中,在TestOracleCrud中对函数进行测试。