package com.ctl.util;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
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.Queue;
import com.ctl.bean.Orders;
/**
* @author Administrator
* @category
*/
public class DButils {
private static String driver;
private static String url;
private static String username;
private static String password;
private static Connection conn;
private static ThreadLocal<Connection> connHolder = new ThreadLocal<Connection>();
static {
driver = ConfigUtils.getType("mysql.driver");
url = ConfigUtils.getType("mysql.url");
username = ConfigUtils.getType("mysql.username");
password = ConfigUtils.getType("mysql.password");
try {
Runtime.getRuntime().exec("net start mysql");
} catch (IOException e) {
e.printStackTrace();
}
}
static class KeyValue {
Object key;
Object value;
public Object getKey() {
return key;
}
public void setKey(Object key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public KeyValue() {
super();
}
public KeyValue(Object key, Object value) {
super();
this.key = key;
this.value = value;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.key + ":" + this.value;
}
}
/**
*
* @return Connection
* @throws SQLException
* @throws ClassNotFoundException
*/
public static Connection getConnection() throws SQLException,
ClassNotFoundException {
conn = connHolder.get();
if (conn == null || conn.isClosed()) {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
conn.setAutoCommit(false);
connHolder.set(conn);
}
return conn;
}
/**
* @category 根据sql得到记录总数
* @param sql
* @return int 如果返回-1代表出错
*/
public static int getCount(String sql) {
try {
ResultSet rs = getConnection().createStatement().executeQuery(sql);
if (rs.next()) {
return rs.getInt(1);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
}
/**
* @category close Connection
* @throws SQLException
*/
public static void close() throws SQLException {
conn.close();
connHolder.set(null);
}
public static int createTable(Class c) {
String tableName = c.getSimpleName().toLowerCase();// person
return 0;
}
/**
*
* @param c
* 参数例如Person.class
* @param obj
* 参数例如 person obj为某一实例对象 // Person person=new Person();
* @category 该方法用于向数据库中插入条数据 插入的对象是一个实体类的对象
*/
public static void insertEntity(Class c, Object obj) {
// System.out.println("1");
if (obj == null || c.getSimpleName().equals(obj.getClass().getName()))
return;
Field[] fields = obj.getClass().getDeclaredFields();
int fieldSize = fields.length;
String tableName = c.getSimpleName().toLowerCase();// person
String[] types1 = { "int", "java.lang.String", "boolean", "char",
"float", "double", "long", "short", "byte", "date" };
String[] types2 = { "java.lang.Integer", "java.lang.String",
"java.lang.Boolean", "java.lang.Character", "java.lang.Float",
"java.lang.Double", "java.lang.Long", "java.lang.Short",
"java.lang.Byte", "java.util.Date" };
StringBuffer sql = new StringBuffer("replace into " + tableName
+ " values(");
for (int i = 0; i < fieldSize; i++) {
sql.append("?,");
}
sql.deleteCharAt(sql.length() - 1);
sql.append(")");
System.out.println(sql);
PreparedStatement ps = null;
try {
ps = getConnection().prepareStatement(sql.toString());
for (int j = 0; j < fieldSize; j++) {
fields[j].setAccessible(true);
for (int i = 0; i < types1.length; i++) {
if (fields[j].getType().getName()
.equalsIgnoreCase(types1[i])
|| fields[j].getType().getName()
.equalsIgnoreCase(types2[i])) {
if (fields[j].get(obj) != null
&& !"".equals(fields[j].get(obj))
&& !"null".equals(fields[j].get(obj))) {
System.out.print(fields[j].getName() + ":"
+ fields[j].get(obj) + " ");
ps.setObject(j + 1, fields[j].get(obj));
} else {
System.out.print(fields[j].getName() + ":"
+ fields[j].get(obj) + " ");
ps.setObject(j + 1, null);
}
}
}
}
ps.executeUpdate();
getConnection().commit();
System.out.println("\nsql:" + ps.toString().split(":")[1].trim());
} catch (Exception e1) {
e1.printStackTrace();
}
}
/**
* @category 根据传入的主键值返回一个实体对象
* @param c
* for example Person.class
* @param primaryKeys
* primaryKeys为主键,参数顺序和表中保持一致 如果id, name 为主键 类名为Person 则
* getEntity(Person.class,1,"name")
* @return Object
*/
public static Object getEntity(Class c, Object... primaryKeys) {
PreparedStatement ps = null;
ResultSet rs = null;
DatabaseMetaData dmd = null;
Object obj = null;// 要返回的对象
String tableName = c.getSimpleName().toLowerCase();// person 表的名字
List primaryKeyNameList = new ArrayList();// 存放从表中获取的主键
Field[] fields = c.getFields();// 获取所有的属性
Method[] methods = null;
if (fields.length == 0) {// 当类的属性都是private时
// fields=c.getDeclaredFields();//获取所有的private属性
methods = c.getDeclaredMethods();// 获取get set 方法
}
StringBuilder sql = new StringBuilder("select * from " + tableName
+ " where ");
try {
obj = c.newInstance();
if (isTableExist(tableName) < 1) {
System.err.println("表不存在");
return obj;
}
dmd = getConnection().getMetaData();
rs = dmd.getPrimaryKeys(null, null, tableName);
while (rs.next()) {// 获取所有的主键
sql.append(rs.getObject(4) + "=?");
sql.append(" and ");
primaryKeyNameList.add(rs.getObject(4));// 将从表中获取的 主键字段存到 list中,
// 主键位于表中第几列=rs.getString(5)
}
sql.delete(sql.length() - 4, sql.length());
if (!sql.toString().contains("where")) {
System.err.println("没有找到主键");
return obj;
}
ps = (PreparedStatement) getConnection().prepareStatement(
sql.toString());
for (int l = 0; l < primaryKeyNameList.size(); l++) {
ps.setObject(l + 1, primaryKeys[l]);
}
rs = ps.executeQuery();
System.out.println(ps.toString().split(":")[1]);
List<String> tableColumns = getColumns(c);
if (rs.next()) {
if (fields.length > 0) {// 如果类 的属性为public
for (int k = 0; k < fields.length; k++) {
fields[k].set(obj, rs.getObject(k + 1));
}
} else {// 如果类 的属性为private
for (int k = 0; k < methods.length; k++) {
for (int i = 0; i < tableColumns.size(); i++) {
if (methods[k].getName().equalsIgnoreCase(
"set" + tableColumns.get(i))) {
methods[k].invoke(obj,
rs.getObject(tableColumns.get(i)));
}
}
}
}
}
rs.close();
ps.close();
rs = null;
ps = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return obj;
}
/**
*
* @param tableName
* 标的名字
* @category 表不存在 1表存在
* @return 0表不存在 >=1表存在
*/
public static int isTableExist(String tableName) {
int v = getCount("SELECT count(table_name) FROM information_schema.TABLES WHERE table_name=‘"
+ tableName + "‘ ");
if (v >= 1) {
return v;
} else {
System.err.println("表 不存在 table not exist");
return 0;
}
}
/**
*
* @category 获取某个表中所有的列名
* @param c
* Person.class (类名与表名一致)
* @return List
*/
public static List<String> getColumns(Class c) {
List<String> list = new ArrayList<String>();
String tableName = c.getSimpleName().toLowerCase();// person 表的名字
if (isTableExist(tableName) < 1) {
System.err.println("talbe is not exist");
return list;
}
String sql = "select COLUMN_NAME from information_schema.columns where table_name=‘"
+ tableName + "‘";
try {
ResultSet rs = getConnection().createStatement().executeQuery(sql);
while (rs.next()) {
if (!list.contains(rs.getString(1))) {
list.add(rs.getString(1));// 防止不同数据库中有相同的表名
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* @category 查找某一列的所有值
* @param c
* Person.class
* @param columnName
* 要查找的某一列的列名
* @return List<String> 返回某一列的所有值
*/
public static List<String> getColumnData(Class c, String columnName) {
if (!getColumns(c).contains(columnName)) {
System.err.println("列名‘" + columnName + "‘不存在");
return null;
}
List<String> list = new ArrayList<String>();
String tableName = c.getSimpleName().toLowerCase();// person 表的名字
if (isTableExist(tableName) < 1) {
System.err.println("talbe is not exist");
return list;
}
String sql = "select " + columnName + " from " + tableName;
try {
ResultSet rs = getConnection().createStatement().executeQuery(sql);
while (rs.next()) {
list.add(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* @category 根据条件查询 返回where columnName=value
* @param c
* Person.class 且Person 所有的属性必须全为为public类型或者全部为private
* @param columnName
* 表中的某字段
* @param value
* columnName对应的值
* @return List
*/
public static List getEntitys(Class c, String columnName, Object value) {
if (!getColumns(c).contains(columnName)) {
System.err.println("列名‘" + columnName + "‘不存在");
return null;
}
List list = new ArrayList();
PreparedStatement ps = null;
ResultSet rs = null;
String tableName = c.getSimpleName().toLowerCase();// person 表的名字
Field[] fields = c.getFields();// 获取所有的public属性
Method[] methods = null;
if (fields.length == 0) {
// fields=c.getDeclaredFields();//获取所有的private属性
methods = c.getDeclaredMethods();// 获取get set 方法
}
StringBuilder sql = new StringBuilder("select * from " + tableName
+ " where " + columnName + "=?");
try {
if (isTableExist(tableName) == 0) {
System.err.println("表不存在");
return list;
}
ps = (PreparedStatement) getConnection().prepareStatement(
sql.toString());
ps.setObject(1, value);
rs = ps.executeQuery();
System.out.println("\n" + ps.toString().split(":")[1]);
Object obj = null;
while (rs.next()) {
obj = c.newInstance();
if (fields.length > 0) {// 如果类 的属性为public
for (int k = 0; k < fields.length; k++) {
fields[k].set(obj, rs.getObject(k + 1));
}
} else {// 如果类 的属性为private
for (int k = 0; k < methods.length / 2; k++) {
methods[k * 2].invoke(obj, rs.getObject(k + 1));
}
}
list.add(obj);
}
rs.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
rs = null;
ps = null;
}
return list;
}
/**
* @see 获取所有的数据
* @param c Person.class
* @return List所有的数据
*/
public static List getAllEntitys(Class c){
String tableName = c.getSimpleName().toLowerCase();// person 表的名字
if(isTableExist(tableName)<1){
System.err.println("表‘"+tableName+"‘不存在");
return null;
}
List list = new ArrayList();
PreparedStatement ps = null;
ResultSet rs = null;
Field[] fields = c.getFields();// 获取所有的public属性
if (fields.length == 0) {
// fields=c.getDeclaredFields();//获取所有的private属性
fields = c.getDeclaredFields();// 获取get set 方法
}
StringBuilder sql = new StringBuilder("select * from " + tableName);
try {
if (isTableExist(tableName) == 0) {
System.err.println("表不存在");
return list;
}
ps = (PreparedStatement) getConnection().prepareStatement(
sql.toString());
rs = ps.executeQuery();
System.out.println("\n" + ps.toString().split(":")[1]);
Object obj = null;
while (rs.next()) {
obj = c.newInstance();
for (int k = 0; k < fields.length; k++) {
fields[k].setAccessible(true);
fields[k].set(obj, rs.getObject(k + 1));
}
list.add(obj);
}
rs.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
rs = null;
ps = null;
}
return list;
}
/**
* @see 获取数据中的某几条记录
* @param c Person.class
* @param fromNumber 从数据库的第几条开始(0,1,2,3)
* @param number 从fromNumber开始获取多少行
* @return List
*/
public static List getEntitysLimit(Class c,int fromNumber,int number){
String tableName = c.getSimpleName().toLowerCase();// person 表的名字
if(isTableExist(tableName)<1){
System.err.println("表‘"+tableName+"‘不存在");
return null;
}
List list = new ArrayList();
PreparedStatement ps = null;
ResultSet rs = null;
Field[] fields = c.getFields();// 获取所有的public属性
if (fields.length == 0) {
// fields=c.getDeclaredFields();//获取所有的private属性
fields = c.getDeclaredFields();// 获取get set 方法
}
StringBuilder sql = new StringBuilder("select * from " + tableName).append(" limit ?,?");
try {
if (isTableExist(tableName) == 0) {
System.err.println("表不存在");
return list;
}
ps = (PreparedStatement) getConnection().prepareStatement(
sql.toString());
ps.setInt(1, fromNumber);
ps.setInt(2, number);
rs = ps.executeQuery();
System.out.println("\n" + ps.toString().split(":")[1]);
Object obj = null;
while (rs.next()) {
obj = c.newInstance();
for (int k = 0; k < fields.length; k++) {
fields[k].setAccessible(true);
fields[k].set(obj, rs.getObject(k + 1));
}
list.add(obj);
}
rs.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
rs = null;
ps = null;
}
return list;
}
/**
* @category 返回表中所有的主键
* @param c
* Person.class
* @return list
*/
public static List<String> getPrimaryKeys(Class c) {
String tableName = c.getSimpleName().toLowerCase();// person 表的名字
ResultSet rs = null;
List<String> list = new ArrayList<String>();
try {
rs = getConnection().getMetaData().getPrimaryKeys(null, null,
tableName);
while (rs.next()) {
list.add(rs.getString(4));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* @category 根据主键删除数据
* @param c
* Person.class
* @param primaryKey
* 按表中主键删除 如果主键为id。name
* 则deleteByPrimaryKey(Person.class,1,"ctl");
*/
public static void deleteByPrimaryKey(Class c, Object... primaryKey) {
String tableName = c.getSimpleName().toLowerCase();// person 表的名字
List<String> primaryKeysList = getPrimaryKeys(c);
StringBuilder sb = new StringBuilder("delete from " + tableName
+ " where ");
for (int i = 0; i < primaryKeysList.size(); i++) {
sb.append(primaryKeysList.get(i) + "=? and ");
}
sb.delete(sb.length() - 4, sb.length());
PreparedStatement ps = null;
try {
ps = getConnection().prepareStatement(sb.toString());
for (int i = 0; i < primaryKeysList.size(); i++) {
ps.setObject(i + 1, primaryKey[i]);
}
ps.executeUpdate();
getConnection().commit();
System.out.println(ps.toString().split(":")[1].trim());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @see 删除列名为columnName列值为columnValue的数据
* @param c
* Person.class
* @param columnName
* 列名
* @param columnValue
* 列名对应的值
*/
public static void deleteByColumn(Class c, String columnName,
Object columnValue) {
if (!getColumns(c).contains(columnName)) {
System.err.println("列名‘" + columnName + "‘" + "不存在");
return;
}
String tableName = c.getSimpleName().toLowerCase();// person 表的名字
StringBuilder sql = new StringBuilder("delete from ").append(tableName)
.append(" where ").append(columnName + "=?");
try {
PreparedStatement ps = getConnection().prepareStatement(
sql.toString());
ps.setObject(1, columnValue);
// ps.setObject(2,columnValue );
int result = ps.executeUpdate();
System.out.println(ps.toString().split(":")[1].trim());
if (result >= 1) {
getConnection().commit();
System.out.println("删除" + result + "条记录");
} else {
System.out.println("删除" + result + "条记录");
getConnection().rollback();
}
} catch (Exception e) {
System.err.println("delete error");
e.printStackTrace();
}
}
/**
* @category 从实体类对象中获取主键的列名和value 利用的是filed获取
* @param c
* Person.class
* @param obj
* 实体对象
* @return 从数据库中获取主键 然后与实体类相匹配,返回对象中的主键名和值
*/
public static List<KeyValue> getEntityPrimaryKeyValueField(Class c,
Object obj) {
List<KeyValue> keyValues = new ArrayList<KeyValue>();
List<String> primaryKeys = getPrimaryKeys(c);
Field[] fields = c.getFields();// 获取所有的属性
for (int i = 0; i < fields.length; i++) {// 所有属性为public
try {
for (int j = 0; j < primaryKeys.size(); j++) {
if (primaryKeys.get(j)
.equalsIgnoreCase(fields[i].getName())) {
KeyValue kv = new KeyValue();
kv.setKey(fields[i].getName());
kv.setValue(fields[i].get(obj));
keyValues.add(kv);
System.out.println(fields[i].getName() + ":"
+ fields[i].get(obj));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (fields.length == 0) {// 当类的属性都是private时
// fields=c.getDeclaredFields();//获取所有的private属性
fields = c.getDeclaredFields();// //获得对象所有属性
for (int i = 0; i < fields.length; i++) {
try {
fields[i].setAccessible(true);// 修改访问权限 可以访问private
for (int j = 0; j < primaryKeys.size(); j++) {
if (primaryKeys.get(j).equalsIgnoreCase(
fields[i].getName())) {
KeyValue kv = new KeyValue();
kv.setKey(fields[i].getName());
kv.setValue(fields[i].get(obj));// 读取属性值
keyValues.add(kv);
System.out.println(fields[i].getName() + ":"
+ fields[i].get(obj));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return keyValues;
}
/**
* @category 从实体类对象中获取主键的列名和value 利用的是Method get方法获取
* @param c
* Person.class
* @param obj
* 实体对象
* @return 从数据库中获取主键 然后与实体类相匹配,返回对象中的主键名和值
*/
public static List<KeyValue> getEntityPrimaryKeyValueMethod(Class c,
Object obj) {
List<KeyValue> keyValues = new ArrayList<KeyValue>();
List<String> primaryKeys = getPrimaryKeys(c);
Field[] fields = c.getFields();// 获取所有的属性
for (int i = 0; i < fields.length; i++) {// 所有属性为public
try {
for (int j = 0; j < primaryKeys.size(); j++) {
if (primaryKeys.get(j)
.equalsIgnoreCase(fields[i].getName())) {
KeyValue kv = new KeyValue();
kv.setKey(fields[i].getName());
kv.setValue(fields[i].get(obj));
keyValues.add(kv);
System.out.println(fields[i].getName() + ":"
+ fields[i].get(obj));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (fields.length == 0) {// 当类的属性都是private时
// fields=c.getDeclaredFields();//获取所有的private属性
fields = c.getDeclaredFields();// //获得对象所有属性
for (int i = 0; i < fields.length; i++) {
try {
fields[i].setAccessible(true);// 修改访问权限 可以访问private
for (int j = 0; j < primaryKeys.size(); j++) {
if (primaryKeys.get(j).equalsIgnoreCase(
fields[i].getName())) {
KeyValue kv = new KeyValue();
kv.setKey(fields[i].getName());
kv.setValue(fields[i].get(obj));// 读取属性值
keyValues.add(kv);
System.out.println(fields[i].getName() + ":"
+ fields[i].get(obj));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return keyValues;
}
/**
* @category 从实体类对象中按顺序获取所有主键的value
* @param c
* Person.class
* @param obj
* 实体对象
* @return 从数据库中获取主键 然后与实体类相匹配,返回对象中的主键值
*/
public static List<Object> getEntityPKValues(Class c, Object obj) {
List<Object> keyValues = new ArrayList<Object>();
List<String> primaryKeys = getPrimaryKeys(c);
Field[] fields = c.getFields();// 获取所有的属性
for (int i = 0; i < fields.length; i++) {// 所有属性为public
try {
for (int j = 0; j < primaryKeys.size(); j++) {
if (primaryKeys.get(j)
.equalsIgnoreCase(fields[i].getName())) {
keyValues.add(fields[i].get(obj));
System.out.println(fields[i].getName() + ":"
+ fields[i].get(obj));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (fields.length == 0) {// 当类的属性都是private时
// fields=c.getDeclaredFields();//获取所有的private属性
fields = c.getDeclaredFields();// //获得对象所有属性
for (int i = 0; i < fields.length; i++) {
try {
fields[i].setAccessible(true);// 修改访问权限 可以访问private
for (int j = 0; j < primaryKeys.size(); j++) {
if (primaryKeys.get(j).equalsIgnoreCase(
fields[i].getName())) {
keyValues.add(fields[i].get(obj));
System.out.println(fields[i].getName() + ":"
+ fields[i].get(obj));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return keyValues;
}
/**
* @see 如果有主键则执行更行,没有主键则执行插入操作
* @category 将实体类对象跟新到数据库中,如果对象中的属性与数据中不一致则更新,对象某属性为空则不更改该属性
* @param c
* Person.class
* @param obj
* person
*/
public static void updateEntity(Class c, Object obj) {
String tableName = c.getSimpleName().toLowerCase();// person 表的名字
List<String> primaryKeys = getPrimaryKeys(c);
List<KeyValue> keyValues = getEntityPrimaryKeyValueField(c, obj);
List<String> columns = getColumns(c);
List<Object> values = getEntityPKValues(c, obj);
Object tableDate = getEntity(c, values.toArray(new Object[] {}));
// System.out.println(o);
Field[] fields = c.getFields();// 获取所有的属性
System.out.println("数据库比对前:" + obj);
System.out.println("数据库中数据:" + tableDate);
for (int i = 0; i < fields.length; i++) {// 所有属性为public
try {
for (int j = 0; j < columns.size(); j++) {
if (columns.get(j).equalsIgnoreCase(fields[i].getName())) {
System.out.println(fields[i].getName() + ":"
+ fields[i].get(obj));
if (fields[i].get(obj) == null) {
fields[i].set(obj, fields[i].get(tableDate));
} else if (!fields[i].get(obj).equals(
fields[i].get(tableDate))) {
continue;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (fields.length == 0) {// 当类的属性都是private时
// fields=c.getDeclaredFields();//获取所有的private属性
fields = c.getDeclaredFields();// //获得对象所有属性
for (int i = 0; i < fields.length; i++) {
try {
fields[i].setAccessible(true);// 修改访问权限 可以访问private
for (int j = 0; j < columns.size(); j++) {
if (columns.get(j)
.equalsIgnoreCase(fields[i].getName())) {
System.out.println(fields[i].getName() + ":"
+ fields[i].get(obj));
if (fields[i].get(obj) == null) {
fields[i].set(obj, fields[i].get(tableDate));
} else if (!fields[i].get(obj).equals(
fields[i].get(tableDate))) {
continue;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
System.out.println("数据库比对后:" + obj);
insertEntity(c, obj);
}
public static void main(String[] args) {
}
}
DButils工具类可以用来获取数据库连接向数据库插入更新删除对象,布布扣,bubuko.com
DButils工具类可以用来获取数据库连接向数据库插入更新删除对象