依靠反射来个Dbutils
闲来无事,写个dbutils玩玩,不完善,满足基本增删改查,上代码
1、Dbutils
package db; import annotation.Table;
import java.util.*;
import java.sql.*;
import java.lang.reflect.Field; /**
*
* @author xjy
* @param <T>
*/
public class DbUtil<T> { private static DataBase dataBase = null;
private static Connection con = null;
private static Statement st = null; public DbUtil() {
dataBase = new DataBase();
} @SuppressWarnings("null")
public List<T> getAll(T bean) throws Exception { List<T> list = new ArrayList<>();
Class<T> clazz = (Class<T>) bean.getClass();
Table table = clazz.getDeclaredAnnotation(Table.class);
String name = table.name(); String tableName;
if (!"".equals(name)) {
tableName = name;
} else {
tableName = clazz.getSimpleName().toLowerCase();
} StringBuilder sql = new StringBuilder("select * from " + tableName); if (bean != null) {
sql.append(" where ");
Field[] declaredFields = clazz.getDeclaredFields(); for (Field declaredField : declaredFields) {
//打开私有访问
declaredField.setAccessible(true);
String name1 = declaredField.getName();
Object value = declaredField.get(bean);
if (value != null && !"id".equals(name1)) {
sql.append(name1).append("='").append(value).append("' and ");
}
}
sql.append("1=1");
} con = dataBase.getConnection();
st = dataBase.getStatement(); ResultSet rs = st.executeQuery(sql.toString()); Field[] fields = clazz.getDeclaredFields();
while (rs.next()) { T t = clazz.newInstance(); for (Field field : fields) {
String fName = field.getName();
String str = rs.getString(fName);
field.setAccessible(true); // 如果类型是Integer
if (field.getGenericType().toString().equals("class java.lang.Integer")) {
field.set(t, Integer.valueOf(str));
} else {
field.set(t, str);
} } list.add(t);
} return list;
} public int add(T bean) throws Exception {
con = dataBase.getConnection();
st = dataBase.getStatement();
Class<T> clazz = (Class<T>) bean.getClass();
Table table = clazz.getDeclaredAnnotation(Table.class);
String name = table.name(); String tableName;
if (!"".equals(name)) {
tableName = name;
} else {
tableName = clazz.getSimpleName().toLowerCase();
} Field[] fields = clazz.getDeclaredFields(); StringBuilder sql = new StringBuilder("insert into " + tableName + "("); for (Field field : fields) {
String fName = field.getName();
if (!"id".equals(fName)) {
sql.append(fName).append(","); }
} sql.deleteCharAt(sql.length() - 1).append(") values("); Field[] declaredFields = clazz.getDeclaredFields(); for (Field declaredField : declaredFields) { if (!"id".equals(declaredField.getName())) {
//打开私有访问
declaredField.setAccessible(true);
Object value = declaredField.get(bean);
sql.append("'").append(value).append("',");
} } sql.deleteCharAt(sql.length() - 1).append(")");
int result = 0; try {
result = st.executeUpdate(sql.toString());
} catch (SQLException se) {
System.out.println(se.getMessage());
} finally { }
return result;
} @SuppressWarnings("FinallyDiscardsException")
public List<Map<String, Object>> querySql(String sql) {
List<Map<String, Object>> list = new ArrayList<>(); con = dataBase.getConnection();
st = dataBase.getStatement();
@SuppressWarnings("UnusedAssignment")
ResultSet rs = null;
try {
rs = st.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData(); //获得结果集结构信息,元数据
int columnCount = md.getColumnCount(); //获得列数
while (rs.next()) {
Map<String, Object> rowData = new HashMap<>();
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
list.add(rowData);
}
} catch (SQLException e) {
System.out.println(e.toString()); } finally {
dataBase.closeConnection();
return list;
}
} @SuppressWarnings("FinallyDiscardsException")
public int executeSql(String sql) {
con = dataBase.getConnection();
st = dataBase.getStatement();
int result = 0;
try {
result = st.executeUpdate(sql);
} catch (SQLException se) {
System.out.println(se.getMessage());
} finally {
dataBase.closeConnection();
return result;
}
} @SuppressWarnings("MismatchedReadAndWriteOfArray")
public int update(T bean) throws Exception {
con = dataBase.getConnection();
st = dataBase.getStatement();
Class<T> clazz = (Class<T>) bean.getClass();
Table table = clazz.getDeclaredAnnotation(Table.class);
String name = table.name(); String tableName;
if (!"".equals(name)) {
tableName = name;
} else {
tableName = clazz.getSimpleName().toLowerCase();
} StringBuilder sql = new StringBuilder("update " + tableName + " set "); Field[] declaredFields = clazz.getDeclaredFields(); for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
//打开私有访问
String name1 = declaredField.getName();
Object value = declaredField.get(bean);
if (value != null && !"id".equals(name1)) {
sql.append(name1).append("='").append(value).append("',");
}
}
Field field1 = clazz.getDeclaredField("id");
field1.setAccessible(true); sql.deleteCharAt(sql.length() - 1).append(" where id =").append(field1.get(bean)); int result = 0; try {
result = st.executeUpdate(sql.toString());
} catch (SQLException se) {
System.out.println(se.getMessage());
} finally {
}
return result;
}
}
2、注解Table
package annotation; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
*
* @author xjy
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table { public String name() default ""; }
3、database,获取连接等,这里用的sqlserver,其他自己发挥咯
package db; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement; /**
*
* @author Administrator
*/
public class DataBase { private String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://127.0.0.1:1433;databaseName=db_car";
private String userName = "sa";
private String userPasswd = "123456";
private Connection connection;
private Statement statement;
public DataBase(){
try {
Class.forName(driverName);
}
catch (ClassNotFoundException cnfex){
System.err.println("装载 JDBC/ODBC 驱动程序失败。");
cnfex.printStackTrace();
System.exit(1);
}
}
//取得与数据库的连接
public Connection getConnection(){
try {
//捕获连接数据库异常
connection = DriverManager.getConnection(url, userName, userPasswd);
}
catch (SQLException sqlex){
System.err.println("无法连接数据库");
sqlex.printStackTrace();
System.exit(1);
}
finally {
return connection;
}
}
//取得 statement
public Statement getStatement(){
try {
if (connection != null){
statement = connection.createStatement();
}
}
catch (SQLException sqlex){
System.err.println("无法取得 Statement");
sqlex.printStackTrace();
System.exit(1);
}
finally{
return statement;
}
}
public void closeConnection(){
try {
if (null != statement){
statement.close();
}
if (null != connection){
connection.close();
}
statement = null;
connection = null;
}
catch (Exception e){
e.printStackTrace();
}
}
}
所需驱动文件:https://files.cnblogs.com/files/xujingyang/sqljdbc4.zip
顺便说下,开发工具玩的是NetBeans
依靠反射来个Dbutils的更多相关文章
- dbutils中实现数据的增删改查的方法,反射常用的方法,绝对路径的写法(杂记)
jsp的三个指令为:page,include,taglib... 建立一个jsp文件,建立起绝对路径,使用时,其他jsp文件导入即可 导入方法:<%@ include file="/c ...
- 利用反射和ResultSetMetaData实现DBUtils的基本功能
DBUtils大大简化了JDBC的书写,极大的提高了开发效率,和数据库连接池一起,简化了JDBC开发的流程.简易的自定义数据库连接池可以通过装饰者设计模式和动态代理模式得到很简单的实现,那么DBUti ...
- 反射模拟DbUtils实现ResultSet转成Bean实例
前几天接触到了apache的一个小框架DbUtils,真的被其优雅的设计所震撼到了,尤其是其中的 MyBean mybean = QueryRunner.query(sqlConnection,sql ...
- 使用Java封装一个DBUtils类(反射)
刚开始学JavaWeb时,我是调用N个setter方法将从数据库中查询出的数据封装成JavaBean的,极其繁琐. 后来了解SpringJDBC后,发现它提供的接口非常简单,然后就想自己封装一个简单的 ...
- 【Java EE 学习 17 上】【dbutils和回调函数】
一.dbutils的核心就是回调函数,可以说如果没有回调函数的思想,dbutils是不可能被开发出来的. 对于dbutils中的QuryRunner类,向该类的query方法提供不同的参数,可以得到不 ...
- 【Java EE 学习 24 下】【注解在数据库开发中的使用】【反射+注解+动态代理在事务中的应用service层】
一.使用注解可以解决JavaBean和数据库中表名不一致.字段名不一致.字段数量不一致的问题. 1.Sun公司给jdbc提供的注解 @Table.@Column.@Id.@OneToMany.@One ...
- DbUtils是Apache出品一款简化JDBC开发的工具类
DbUtils - DbUtils是Apache出品一款简化JDBC开发的工具类 - 使用DbUtils可以让我们JDBC的开发更加简单 - DbUtils的使用: ...
- JNDI和在tomcat中配置DBCP连接池 元数据的使用 DBUtils框架的使用 多表操作
1 JNDI和在tomcat中配置DBCP连接池 JNDI(Java Naming and Directory Interface),Java命名和目录接口,它对应于J2SE中的javax.namin ...
- 反射机制及开源框架xUitls的使用,使用HttpUtils通过断点续传下载文件
反射: Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法: 对于任意一个对象,都能够调用它的任意一个方法和属性 Java反射机制主要提供下面几种用途: 1•在运行时判断 ...
随机推荐
- Cucumber 之Gherkin
1.Gherkin简介: Cucumber是一个解释程序,就像ruby命令执行解释 .rb文件里的Ruby代码一样,Cucumber用来执行解释 .feature文件里的Gehrkin代码. 2. ...
- C# winform中自定义用户控件 然后在页面中调用用户控件的事件
下面是用户控件的代码: using System; using System.Collections.Generic; using System.ComponentModel; using Syste ...
- STMM32 ‘&’ 操作
if(0x04 == (new_cfg&0x04)){ sys_cfg_msg.pps_cfg = ; cn_save_data[cn_save_index_stp].hash= ; sys_ ...
- 单机数据库优化的一些实践(mysql)
数据库优化有很多可以讲,按照支撑的数据量来分可以分为两个阶段:单机数据库和分库分表,前者一般可以支撑500W或者10G以内的数据,超过这个值则需要考虑分库分表.另外,一般大企业面试往往会从单机数据库问 ...
- 如何使用JSON格式 POST数据到服务器
1. JSON的数据格式a) 按照最简单的形式,可以用下面这样的 JSON 表示名称/值对: { "firstName": "Brett" } b) 可以创建包 ...
- 页面加载完之后在执行js代码
把代码写在 window.onload = function () { //js代码 //此处js代码是页面完全加载完之后执行 } 即可. 例: <script type="text/ ...
- 基于IAR和STM32的uCOS-II移植
网上基于MDK的移植数不胜数,但是基于IAR的移植几乎没有,因为官方的例程就是基于IAR的,所以移植起来很简单,没人介绍,但还是得小心谨慎,一不小心就出错,对于新手来说,查找错误可不是那么容易的.IA ...
- AT指令(二)
1.常用操作1.1 AT命令解释:检测 Module 与串口是否连通,能否接收 AT 命令:命令格式:AT<CR>命令返回:OK (与串口通信正常) (无返回,与串 ...
- 如何使用 J2EE 连接器架构实现企业应用
JCA (J2EE 连接器架构,javaConnector Architecture)是对J2EE标准集的重要补充.因为它注重的是将Java程序连接到非Java程序和软件包中间件的开发.连接器特指基于 ...
- PTA 1005 Spell It Right (20)(20 分)水题
1005 Spell It Right (20)(20 分) Given a non-negative integer N, your task is to compute the sum of al ...