mysql,Jdbc工具类,只需一条sql实现简单查询
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List; import com.mysql.jdbc.PreparedStatement;
/**
*
* 类名: JdbcUtils
* 包名: com.hospital.test.utils
* 作者: Zhangyf
* 时间: 2019年3月7日 下午5:15:00
* 描述: TODO(请在此处详细描述类)
* @since 1.0.0
*
* 修改历史 :
* 1. [2019年3月7日]新建类 by Zhangyf
*
* @param <T>
*/
public abstract class JdbcUtils<T> {
private String jdbcUrl; private String user; private String password; public String getJdbcUrl() {
return jdbcUrl;
}
/**
* 数据库链接地址
*
* 参数: @param jdbcUrl
* 返回类型: void
* @exception
* @since 1.0.0
*/
public void setJdbcUrl(String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
} public String getUser() {
return user;
}
/**
*
* 数据库连接用户名
*
* 参数: @param user
* 返回类型: void
* @exception
* @since 1.0.0
*/
public void setUser(String user) {
this.user = user;
} public String getPassword() {
return password;
}
/**
*
* 数据库连接密码
*
* 参数: @param password
* 返回类型: void
* @exception
* @since 1.0.0
*/
public void setPassword(String password) {
this.password = password;
} static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError();
}
} public Connection getConnection() throws SQLException {
return DriverManager.getConnection(jdbcUrl, user, password);
} public static void free(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} } /**
* 通过反射的方式给对象赋值
*/
public static Object setValByJavaName(String javaName, Object value, Object obj) {
@SuppressWarnings("rawtypes")
Class c = obj.getClass();
try {
Field f = c.getDeclaredField(javaName);
// 取消语言访问检查
f.setAccessible(true);
//给变量赋值
f.set(obj, value);
} catch (NoSuchFieldException e) {
System.out.println("没有对应字段");
} catch (Exception e) {
e.printStackTrace();
}
return obj;
} public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
output.close();
return output.toByteArray();
} /**
* 根据类型来进行转换
* @throws IOException
*/
private static Object changValueType(ResultSet rs, String t, int i) throws SQLException, IOException {
switch (t) {
case "java.math.BigInteger":
return rs.getLong(rs.getMetaData().getColumnName(i));
case "java.sql.Date":
return rs.getDate(rs.getMetaData().getColumnName(i));
case "java.sql.Timestamp":
return rs.getTimestamp(rs.getMetaData().getColumnName(i));
case "java.lang.Integer":
if ("TINYINT".equals(rs.getMetaData().getColumnTypeName(i))) {
return (byte) rs.getInt(rs.getMetaData().getColumnName(i));
}else if("SMALLINT".equals(rs.getMetaData().getColumnTypeName(i))){
return (short) rs.getInt(rs.getMetaData().getColumnName(i));
}
return rs.getInt(rs.getMetaData().getColumnName(i));
case "java.lang.Boolean":
return rs.getBoolean(rs.getMetaData().getColumnName(i));
case "java.lang.Float":
return rs.getFloat(rs.getMetaData().getColumnName(i));
case "java.math.BigDecimal":
return rs.getBigDecimal(rs.getMetaData().getColumnName(i));
case "java.lang.Double":
return rs.getDouble(rs.getMetaData().getColumnName(i));
case "java.lang.Short":
return rs.getShort(rs.getMetaData().getColumnName(i));
case "java.sql.Time":
return rs.getTime(rs.getMetaData().getColumnName(i));
case "java.sql.Byte":
return rs.getByte(rs.getMetaData().getColumnName(i));
case "[B":
if("BINARY".equals(rs.getMetaData().getColumnTypeName(i))){
byte b = rs.getByte(rs.getMetaData().getColumnName(i));
return new byte[]{b};
}else if("VARBINARY".equals(rs.getMetaData().getColumnTypeName(i))){
byte b = rs.getByte(rs.getMetaData().getColumnName(i));
return new byte[]{b};
}else if("BLOB".equals(rs.getMetaData().getColumnTypeName(i))){
Blob picture = rs.getBlob(i);//得到Blob对象
//开始读入文件
InputStream in = picture.getBinaryStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer)) != -1){
output.write(buffer, 0, len);
}
output.close();
return output.toByteArray();
}
return rs.getString(rs.getMetaData().getColumnName(i));
default:
return rs.getString(rs.getMetaData().getColumnName(i));
}
} /*@SuppressWarnings("rawtypes")
protected abstract Class getEntityClassType();*/
/**
*
* 功能: 查询单条数据
* 描述: 该方法只适合单条数据查询
*
* 参数: @param sql
* 参数: @return
* 参数: @throws SQLException
* 参数: @throws InstantiationException
* 参数: @throws IllegalAccessException
* 参数: @throws IOException
* 返回类型: T
* @exception
* @since 1.0.0
*/
@SuppressWarnings("unchecked")
public T query(String sql) throws SQLException, InstantiationException, IllegalAccessException, IOException {
Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
T t = entityClass.newInstance();
Connection conn = this.getConnection();
PreparedStatement p;
p = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = p.executeQuery();
int col = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 1; i < col+1; i++) {
//System.out.println("name: "+rs.getMetaData().getColumnName(i) + " java-type: " + rs.getMetaData().getColumnClassName(i)+" column-type: "+rs.getMetaData().getColumnTypeName(i));
t = (T) setValByJavaName(rs.getMetaData().getColumnName(i), changValueType(rs, rs.getMetaData().getColumnClassName(i), i), t);
}
}
p.close();
conn.close();
return t;
}
/**
*
* 功能: 批量查询方法
* 描述: 该方法可进行批量查询操作
*
* 参数: @param sql
* 参数: @return
* 参数: @throws SQLException
* 参数: @throws InstantiationException
* 参数: @throws IllegalAccessException
* 参数: @throws IOException
* 返回类型: List<T>
* @exception
* @since 1.0.0
*/
@SuppressWarnings("unchecked")
public List<T> queryList(String sql) throws SQLException, InstantiationException, IllegalAccessException, IOException {
Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
T t = entityClass.newInstance();
List<T> list=new ArrayList<>();
Connection conn = this.getConnection();
PreparedStatement p;
p = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = p.executeQuery();
int col = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 1; i < col; i++) {
//System.out.println("name: "+rs.getMetaData().getColumnName(i) + " java-type: " + rs.getMetaData().getColumnClassName(i)+" column-type: "+rs.getMetaData().getColumnTypeName(i));
t = (T) setValByJavaName(rs.getMetaData().getColumnName(i), changValueType(rs, rs.getMetaData().getColumnClassName(i), i), t);
}
list.add(t);
}
p.close();
conn.close();
return list;
} /**
*
* 功能: 新增或修改
* 描述: update和insert通用
*
* 参数: @param sql
* 参数: @return
* 参数: @throws SQLException
* 返回类型: int
* @exception
* @since 1.0.0
*/
public int insert(String sql) throws SQLException{
Connection conn = this.getConnection();
PreparedStatement p;
p = (PreparedStatement) conn.prepareStatement(sql);
int rs = p.executeUpdate(sql);
p.close();
conn.close();
return rs;
} }
食用方式:
import yxm.zyf.love.entity.PHONE; public class Test {
public static void main(String[] args) {
JdbcUtils<PHONE> t = new JdbcUtils<PHONE>() {
};
t.setJdbcUrl("jdbc:mysql:///epay?characterEncoding=UTF-8");
t.setUser("root");
t.setPassword("123");
//query(t);
//insert(t);
update(t);
} private static <T> void query(JdbcUtils<T> t) {
String sql = "SELECT * FROM phone WHERE id=1";
try {
T user = t.query(sql);
System.out.println(user);
/*List<T> userList = t.queryList(sql);
System.out.println(userList);*/
} catch (Exception e) {
e.printStackTrace();
}
} private static <T> void insert(JdbcUtils<T> t) {
String sql = "INSERT into phone (`name`,`age`,`add`,`time`,`date`,`gmt`,`iphone`,`vivo`,`oppo`,`huawei`,`xiaomi`,`xiaodong`,`xiaoxi`,`xiaohu`,`xiaoqi`)"
+ " values('宇翊','21','23',now(),now(),now(),1,2,3,4,5,6,7,8,9)";
try {
int user = t.insert(sql);
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
}
} private static <T> void update(JdbcUtils<T> t) {
String sql = "update phone set name='予以I' where id=2 ";
try {
int user = t.insert(sql);
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:数据库表的字段名必须要和实体类的属性名一致,数据库里面的BLOB和Text大文本字段没处理好,只是简单的用了String类型接收,后面改进
mysql,Jdbc工具类,只需一条sql实现简单查询的更多相关文章
- JDBC_13_封装JDBC工具类
封装JDBC工具类 代码: import java.sql.*; /** * JDBC工具类,简化JDBC编程 */ public class DBUtil { //工具类中的构造方法都是私有的,因为 ...
- MySQL数据库学习笔记(十一)----DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
- MySQL数据库学习笔记(十)----JDBC事务处理、封装JDBC工具类
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
- MySQL JDBC事务处理、封装JDBC工具类
MySQL数据库学习笔记(十)----JDBC事务处理.封装JDBC工具类 一.JDBC事务处理: 我们已经知道,事务的概念即:所有的操作要么同时成功,要么同时失败.在MySQL中提供了Commit. ...
- java使用注解和反射打造一个简单的jdbc工具类
a simple jdbc tools 如有转载和引用,请注明出处,谢谢 1. 定义我们需要的注解 要想实现对数据库的操作,我们必须知道数据表名以及表中的字段名称以及类型,正如hibernate 使用 ...
- 开源JDBC工具类DbUtils
本篇将会详细地介绍Apache公司的JDBC帮助工具类DbUtils以及如何使用.在上一篇中我们已经通过将以前对dao层使用JDBC操作数据库的冗余代码进行了简易封装形成自己的简单工具类JdbcUti ...
- JDBC基础:JDBC快速入门,JDBC工具类,SQL注入攻击,JDBC管理事务
JDBC基础 重难点梳理 一.JDBC快速入门 1.jdbc的概念 JDBC(Java DataBase Connectivity:java数据库连接)是一种用于执行SQL语句的Java API,可以 ...
- DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)
DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类) 一.DAO模式简介 DAO即Data Access Object,数据访问接口.数据访问:故名思义就是与数据库打交道.夹在业务逻辑与数据 ...
- JDBC工具类连接数据库,模仿登录
## 使用JDBC工具类的原因在使用JDBC连接数据库的时候,加载驱动.获取连接.释放资源等代码是重复的,所有为了提高代码的复用性,我们可以写一个工具类,将数据库驱动加载.获取连接.资源释放的代码封装 ...
随机推荐
- @ConfigurationProperties + @EnableConfigurationProperties
1.ConfigurationProperties 在类上通过@ConfigurationProperties注解声明当前类为属性读取类. 举例: @ConfigurationProperties(p ...
- WebDriver与文件系统
1.屏幕截屏操作:其接口函数是TakesScreenshot.该功能是在运行测试用例的过程中,需要验证某个元素的状态或者显示的数值时,可以将屏幕截取下来进行对比:或者在异常或者错误发生的时候将屏幕截取 ...
- Redis入门到高可用(二十)——Redis Cluster
一.呼唤集群 二.数据分布概论 三.哈希分布 1.节点取余 2.一致性哈希 添加一个node5节点时,只影响n1和n2之间的数据 3.虚拟槽分区 四.基本架构 五.redis clust ...
- JDK 1.8源码阅读 HashMap
一,前言 HashMap实现了Map的接口,而Map的类型是成对出现的.每个元素由键与值两部分组成,通过键可以找对所对应的值.Map中的集合不能包含重复的键,值可以重复:每个键只能对应一个值. 存储数 ...
- 2019.04.12 Head First
第一节 认识python python.exe -V python 会进入解释器 quit()命令会退出解释器 IDEL,一个python的集成开发环境,能够利用颜色突出语法的编辑器,一个调试工具,P ...
- 【Spark-core学习之六】 Spark资源调度和任务调度
环境 虚拟机:VMware 10 Linux版本:CentOS-6.5-x86_64 客户端:Xshell4 FTP:Xftp4 jdk1.8 scala-2.10.4(依赖jdk1.8) spark ...
- 清空nohup日志
#清空nohup日志cat /dev/null > /tpdata/www/wxapp_domain/nohup.out
- Python数据分析Numpy库方法简介(三)
补充: np.ceil()向上取整 3.1向上取整是4 np.floor()向下取整 数组名.resize((m,n)) 重置行列 基础操作 np.random.randn()符合正态分布(钟行/高斯 ...
- 51Nod 1185 威佐夫游戏 V2
有2堆石子.A B两个人轮流拿,A先拿.每次可以从一堆中取任意个或从2堆中取相同数量的石子,但不可不取.拿到最后1颗石子的人获胜.假设A B都非常聪明,拿石子的过程中不会出现失误.给出2堆石子的数量, ...
- button theme
children:[ButtonTheme.bar( child:ButtonBar( children:[ FlatButton... ], ),), ]