1、SqlHelper.java

 import java.lang.reflect.*;
import java.sql.*;
import java.util.*; public class SqlHelper {
// SQL Server
/**
* JDBC驱动名称
*/
public static final String CLASS_NAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
/**
* 数据库连库字符串
*/
public static final String URL = "jdbc:sqlserver://192.168.1.254:1433;databaseName=BBSDB";
/**
* 用户名
*/
public static final String UID = "sa";
/**
* 密码
*/
public static final String PWD = "";
/**
* JDBC驱动类型
*/
public static Class CLS = null; // Oracle
// public static final String CLASS_NAME =
// "oracle.jdbc.driver.OracleDriver";
// public static final String URL =
// "jdbc:oracle:thin:@localhost:1522:accp11g";
// public static final String UID = "system";
// public static final String PWD = "manager";
/**
* 获取数据库连接对象
*
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection() throws ClassNotFoundException,
SQLException {
if (CLS == null) {
CLS = Class.forName(CLASS_NAME);
}
return DriverManager.getConnection(URL, UID, PWD);
} /**
* 执行SQL语句不返回查询的操作,返回受影响的行数
*
* @param sql
* SQL语句
* @return 受影响的行数
* @throws ClassNotFoundException
* @throws SQLException
*/
public static int executeNonQuery(String sql) {
int result = -1;
Connection con = null;
PreparedStatement ps = null;
try {
con = getConnection();
ps = con.prepareStatement(sql);
result = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(con, ps, null);
}
return result;
} /**
* 执行Insert语句,返回Insert成功之后标识列的值
*
* @param sql
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public static int executeIdentity(String sql) {
int identity = -1;
Connection con = null;
Statement ps = null;
ResultSet rs = null;
try {
con = getConnection();
ps = con.createStatement();
ps.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
rs = ps.getGeneratedKeys();
if (rs.next()) {
// identity = rs.getInt("GENERATED_KEYS");
identity = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(con, ps, null);
}
return identity;
} /**
* 执行不返回结果集的存储过程
*
* @param sql
* 存储过程名称
* @param params
* 存储过程参数
* @throws ClassNotFoundException
* @throws SQLException
*/
public static void executeNonQuery(String sql, SqlParameter... params) {
Connection con = null;
CallableStatement cs = null;
try {
con = getConnection();
cs = con.prepareCall(sql);
setSqlParameter(cs, params);
cs.executeUpdate();
getSqlParameter(cs, params);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(con, cs, null);
}
} /**
* 执行返回聚合函数的操作
*
* @param sql
* 含有聚合函数的SQL语句
* @return 聚合函数的执行结果
* @throws SQLException
* @throws ClassNotFoundException
*/
public static int executeScalar(String sql) {
int result = -1;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()) {
result = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(con, ps, rs);
}
return result;
} /**
* 执行返回泛型集合的SQL语句
*
* @param cls
* 泛型类型
* @param sql
* 查询SQL语句
* @return 泛型集合
* @throws ClassNotFoundException
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static <T> List<T> executeList(Class<T> cls, String sql) {
List<T> list = new ArrayList<T>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
T obj = executeResultSet(cls, rs);
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(con, ps, rs);
}
return list;
} /**
* 执行返回泛型集合的存储过程
*
* @param cls
* 泛型类型
* @param sql
* 存储过程名称
* @param params
* 存储过程参数
* @return 泛型集合
* @throws ClassNotFoundException
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static <T> List<T> executeList(Class<T> cls, String sql,
SqlParameter... params) {
List<T> list = new ArrayList<T>();
Connection con = null;
CallableStatement cs = null;
ResultSet rs = null;
try {
con = getConnection();
cs = con.prepareCall(sql);
setSqlParameter(cs, params);
rs = cs.executeQuery();
while (rs.next()) {
T obj = executeResultSet(cls, rs);
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(con, cs, rs);
}
return list;
} /**
* 执行返回泛型类型对象的SQL语句
*
* @param cls
* 泛型类型
* @param sql
* SQL语句
* @return 泛型类型对象
* @throws SQLException
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static <T> T executeEntity(Class<T> cls, String sql) {
T obj = null;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
obj = executeResultSet(cls, rs);
break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(con, ps, rs);
}
return obj;
} /**
* 执行返回泛型类型对象的存储过程
*
* @param cls
* 泛型类型
* @param sql
* SQL语句
* @param params
* 存储过程参数
* @return 泛型类型对象
* @throws SQLException
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static <T> T executeEntity(Class<T> cls, String sql,
SqlParameter... params) {
T obj = null;
Connection con = null;
CallableStatement cs = null;
ResultSet rs = null;
try {
con = getConnection();
cs = con.prepareCall(sql);
setSqlParameter(cs, params);
rs = cs.executeQuery();
while (rs.next()) {
obj = executeResultSet(cls, rs);
break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(con, cs, rs);
}
return obj;
} /**
* 将一条记录转成一个对象
*
* @param cls
* 泛型类型
* @param rs
* ResultSet对象
* @return 泛型类型对象
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
private static <T> T executeResultSet(Class<T> cls, ResultSet rs)
throws InstantiationException, IllegalAccessException, SQLException {
T obj = cls.newInstance();
ResultSetMetaData rsm = rs.getMetaData();
int columnCount = rsm.getColumnCount();
// Field[] fields = cls.getFields();
Field[] fields = cls.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
for (int j = 1; j <= columnCount; j++) {
String columnName = rsm.getColumnName(j);
if (fieldName.equalsIgnoreCase(columnName)) {
Object value = rs.getObject(j);
field.setAccessible(true);
field.set(obj, value);
break;
}
}
}
return obj;
} /**
* 设置存储过程参数名称,参数值,参数方向
*
* @param cs
* @param params
* @throws SQLException
*/
private static void setSqlParameter(CallableStatement cs,
SqlParameter... params) throws SQLException {
if (params != null) {
for (SqlParameter param : params) {
if (param.OutPut) {
String paramName = param.Name;
if (paramName == null || paramName.equals("")) {
cs.registerOutParameter(1, param.Type);// 设置返回类型参数
} else {
cs.registerOutParameter(paramName, param.Type);// 设置输出类型参数
}
} else {
cs.setObject(param.Name, param.Value);// 设置输入类型参数
}
}
}
} /**
* 得到存储过程参数执行结果
*
* @param cs
* @param params
* @throws SQLException
*/
private static void getSqlParameter(CallableStatement cs,
SqlParameter... params) throws SQLException {
for (SqlParameter param : params) {
if (param.OutPut) {
String paramName = param.Name;
if (paramName == null || paramName.equals("")) {
param.Value = cs.getObject(1);// 返回类型参数值
} else {
param.Value = cs.getObject(paramName);// 输出类型参数值
}
}
}
} /**
* 关闭JDBC对象,释放资源。
*
* @param con
* 连接对象
* @param ps
* 命令对象
* @param rs
* 结果集对象
* @throws SQLException
*/
private static void close(Connection con, Statement ps, ResultSet rs) {
try {
rs.close();
if (rs != null) { rs = null;
}
if (ps != null) {
ps.close();
ps = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

SqlHelper

2、SqlParameter.java

 /**
* 存储过程参数类型
* @author Administrator
*
*/
public class SqlParameter {
/**
* 参数名称
*/
public String Name;
/**
* 参数值
*/
public Object Value;
/**
* true表示参数为输出类型
*/
public boolean OutPut;
/**
* 参数类型
*/
public int Type;
/**
* 输入类型参数的构造函数
* @param name 存储过程 输入类型 参数名称
* @param value 存储过程 输入类型 参数值
*/
public SqlParameter(String name,Object value){
this.Name = name;
this.Value= value;
}
/**
* 输出类型参数的构造函数
* @param type 存储过程 输出类型 参数类型
* @param name 存储过程 输出类型 参数名称
*/
public SqlParameter(int type,String name){
this.Name = name;
this.OutPut = true;
this.Type = type;
}
/**
* 返回类型参数的构造函数
* @param type 存储过程 返回类型
*/
public SqlParameter(int type){
this.Name = "";
this.OutPut = true;
this.Type = type;
}
}

SqlParameter

3、Program.java

 import java.util.List;

 public class Program {

     public static void main(String[] args) {
// TODO Auto-generated method stub String sql = "INSERT INTO [dbo].[UserInfo] ([UserName] ,[LoginName] ,[LoginPwd] ,[UserSex] ,[Birthday]) VALUES ('%s','%s','%s','%s','%s')";
sql = String.format(sql, "wyp1","wyp1","wyp1","1","1981-04-21");
int identyValue = SqlHelper.executeIdentity(sql);
System.out.println(String.format("Identity Value:%d",identyValue)); // List<UserInfo> list = SqlHelper.executeList(UserInfo.class, "select * from UserInfo");
// for (UserInfo userInfo : list) {
// System.out.println(String.format(
// "UserInfoId:%d,UserName:%s,LoginName:%s,LoginPwd:%s,UserSex:%s,Birthday:%s",
// userInfo.getUserInfoId(),userInfo.getUserName(),userInfo.getLoginName(),userInfo.getLoginPwd(),userInfo.getUserSex()?"男":"女",DateHelper.toString(userInfo.getBirthday())));
// } // SqlParameter param = new SqlParameter("sortField", "[UserInfoId] DESC");
// List<UserInfo> list = SqlHelper.executeList(UserInfo.class, "{call dbo.UserInfoSelectAll(?)}",param);
// for (UserInfo userInfo : list) {
// System.out.println(String.format(
// "UserInfoId:%d,UserName:%s,LoginName:%s,LoginPwd:%s,UserSex:%s,Birthday:%s",
// userInfo.getUserInfoId(),userInfo.getUserName(),userInfo.getLoginName(),userInfo.getLoginPwd(),userInfo.getUserSex()?"男":"女",DateHelper.toString(userInfo.getBirthday())));
// } // SqlParameter paramSortField = new SqlParameter("sortField", "[UserInfoId] DESC");
// SqlParameter paramPageSize = new SqlParameter("pageSize", 10);
// SqlParameter paramPageIndex = new SqlParameter("pageIndex", 1);
// SqlParameter paramWhere = new SqlParameter("where", "1=1");
// List<UserInfo> list = SqlHelper.executeList(UserInfo.class, "{call dbo.UserInfoSelectByPagerParams(?,?,?,?)}",paramSortField,paramPageSize,paramPageIndex,paramWhere);
// for (UserInfo userInfo : list) {
// System.out.println(String.format(
// "UserInfoId:%d,UserName:%s,LoginName:%s,LoginPwd:%s,UserSex:%s,Birthday:%s",
// userInfo.getUserInfoId(),userInfo.getUserName(),userInfo.getLoginName(),userInfo.getLoginPwd(),userInfo.getUserSex()?"男":"女",DateHelper.toString(userInfo.getBirthday())));
// } // SqlParameter paramWhere = new SqlParameter("where", "1=1");
// SqlParameter paramRecordCount = new SqlParameter(java.sql.Types.INTEGER, "recordCount");
// SqlHelper.executeNonQuery("{call dbo.UserInfoCountByWhere(?,?)}", paramWhere,paramRecordCount);
// if(paramRecordCount.Value instanceof Integer){
// Integer recordCount = (Integer)paramRecordCount.Value;
// System.out.println(String.format("RecordCount:%d",recordCount));
// } // SqlParameter paramWhere = new SqlParameter("where", "1=1");
// SqlParameter paramRecordCount = new SqlParameter(java.sql.Types.INTEGER, "recordCount");
// SqlParameter paramReturnValue = new SqlParameter(java.sql.Types.INTEGER);
// SqlHelper.executeNonQuery("{? = call dbo.UserInfoCountByWhere(?,?)}", paramReturnValue,paramWhere,paramRecordCount);
// if(paramRecordCount.Value instanceof Integer){
// Integer recordCount = (Integer)paramRecordCount.Value;
// System.out.println(String.format("RecordCount:%d",recordCount));
// }
// if(paramReturnValue.Value instanceof Integer){
// Integer returnValue = (Integer)paramReturnValue.Value;
// System.out.println(String.format("ReturnValue:%d",returnValue));
// }
} }

Program

[原创] Java JDBC连接数据库,反射创建实体类对象并赋值数据库行记录(支持存储过程)的更多相关文章

  1. java中的几种实体类对象(PO,VO,DAO,BO,POJO)

    一.PO :(persistant object ),持久对象 可以看成是与数据库中的表相映射的java对象.使用Hibernate来生成PO是不错的选择. 二.VO :(value object) ...

  2. .NET解析xml字符串,通过反射给实体类对象赋值,获取实体类数据列表

    /// <summary> /// 解析xml字符串 转换为实体类列表数据 /// </summary> /// <param name="xmlStr&quo ...

  3. Java 将JSON反射到实体类

    通过服务间调用拿到的数据返回的格式是JSON,如果你当前这个服务有实体数据类型可以对应上,那么就可以轻松愉快的搞定. 如果数据格式对不上,例如这个JSON里面有些数据是我们不想要的,这样我们实体的数据 ...

  4. java将JSON字符串转换为实体类对象,基于net.sf.json实现

    @SuppressWarnings("unchecked") public static <T> T jsonToObject(String jsonString, C ...

  5. JDBC连接数据库反射实现O/R映射

    测试preparedStatement public void testPreparedStatement(){ Connection connection=null; PreparedStateme ...

  6. java 获取实体类对象属性值的方法

    在java中我们要获得实体类对象的属性,一般情况是将实体类中的属性私有化,然后再对外提供get()与set()方法,然后再获取实体类对象的属性的时候先把对象new出来,再用变量名.get()的方法得到 ...

  7. Mybaits 源码解析 (八)----- 全网最详细,没有之一:结果集 ResultSet 自动映射成实体类对象(上篇)

    上一篇文章我们已经将SQL发送到了数据库,并返回了ResultSet,接下来就是将结果集 ResultSet 自动映射成实体类对象.这样使用者就无需再手动操作结果集,并将数据填充到实体类对象中.这可大 ...

  8. 模拟实现MyBatis中通过SQL反射实体类对象功能

    话不多说,直接上干货! package cn.test; import java.lang.reflect.Method; import java.sql.Connection; import jav ...

  9. 使用MyBatis的Generator自动创建实体类和dao的接口与xml

    在实际的项目中其实建立数据库和设计数据库的时候特别重要,而等数据库设计完成之后,根据数据库创建实体类的工作就特别麻烦和繁琐了,不仅很麻烦,而且很浪费时间,不做又不行,这次就找到了一个简单的方法可以让m ...

随机推荐

  1. libuv之介绍

    本人是在研究linux下socket TCP/IP通讯时,用到了一些linux下的API,比如socket, connect, bind,listen, accept等等,简单写个点对点的通讯,直接用 ...

  2. Informatica 常用组件Lookup缓存之五 使用动态查找高速缓存

    对于关系查找,当目标表也是查找表时,可能要配置转换以使用动态高速缓存.PowerCenter 将在处理第一个查找请求时创建高速缓存.它将根据查找条件为传递给转换的每行查询高速缓存.当您使用动态高速缓存 ...

  3. 开源项目-SlideMenu和actionbarsherlock的配置

    SlidingMenu 是github上一个非常优秀的开源库,利用它可以很方便的实现左右侧滑菜单的效果,现在这个基本上应用的标配了,如果一个App没有滑动效果基本上是不可能的,中国人都是本着人无我有, ...

  4. python3 使用openpyxl库读写excel(续)

    官网:https://openpyxl.readthedocs.io/en/stable/

  5. ASM下裸设备的路径更改是否会影响数据库的执行

    通过asm来存储数据库文件,在linux下能够通过asmlib的方式来管理块设备,也能够直接使用裸设备来建立asm磁盘.在asmlib方式下,磁盘设备启动顺序和名称的改变不会影响到asm的使用.但假设 ...

  6. Android-Bundle认知、和Intent的差别

    不时的回过头来看看自己的Andriod学习.实践之路,总发现有些曾经不明确的,如今清楚缘由.也会发现一些之前没怎么关注的.如今看到了 ,很想去深刻了解的. 比方:Bundle. 在一个Activity ...

  7. Andrew Ng Machine Learning 专题【Linear Regression】

    此文是斯坦福大学,机器学习界 superstar - Andrew Ng 所开设的 Coursera 课程:Machine Learning 的课程笔记. 力求简洁,仅代表本人观点,不足之处希望大家探 ...

  8. HDoj-1863-畅通project-并查集

    畅通project Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total ...

  9. 【图解】javaScript组成结构

  10. 免费的Bootstrap等待页面的应用模板

    在线演示 本地下载 这是一款适合移动设备的网页模板,它页面干净小巧.有很多新元素在其中,可以自定义动画和特效.非常酷!