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实现简单查询的更多相关文章

  1. JDBC_13_封装JDBC工具类

    封装JDBC工具类 代码: import java.sql.*; /** * JDBC工具类,简化JDBC编程 */ public class DBUtil { //工具类中的构造方法都是私有的,因为 ...

  2. MySQL数据库学习笔记(十一)----DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  3. MySQL数据库学习笔记(十)----JDBC事务处理、封装JDBC工具类

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  4. MySQL JDBC事务处理、封装JDBC工具类

    MySQL数据库学习笔记(十)----JDBC事务处理.封装JDBC工具类 一.JDBC事务处理: 我们已经知道,事务的概念即:所有的操作要么同时成功,要么同时失败.在MySQL中提供了Commit. ...

  5. java使用注解和反射打造一个简单的jdbc工具类

    a simple jdbc tools 如有转载和引用,请注明出处,谢谢 1. 定义我们需要的注解 要想实现对数据库的操作,我们必须知道数据表名以及表中的字段名称以及类型,正如hibernate 使用 ...

  6. 开源JDBC工具类DbUtils

    本篇将会详细地介绍Apache公司的JDBC帮助工具类DbUtils以及如何使用.在上一篇中我们已经通过将以前对dao层使用JDBC操作数据库的冗余代码进行了简易封装形成自己的简单工具类JdbcUti ...

  7. JDBC基础:JDBC快速入门,JDBC工具类,SQL注入攻击,JDBC管理事务

    JDBC基础 重难点梳理 一.JDBC快速入门 1.jdbc的概念 JDBC(Java DataBase Connectivity:java数据库连接)是一种用于执行SQL语句的Java API,可以 ...

  8. DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)

    DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类) 一.DAO模式简介 DAO即Data Access Object,数据访问接口.数据访问:故名思义就是与数据库打交道.夹在业务逻辑与数据 ...

  9. JDBC工具类连接数据库,模仿登录

    ## 使用JDBC工具类的原因在使用JDBC连接数据库的时候,加载驱动.获取连接.释放资源等代码是重复的,所有为了提高代码的复用性,我们可以写一个工具类,将数据库驱动加载.获取连接.资源释放的代码封装 ...

随机推荐

  1. el表达式(一)

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  2. MAVEN_day01 下载与安装及环境变量的配置

    一.MAVEN简介 MAVEN是apache组织下的一个开源项目,是使用纯java编写的,之用于管理java工程. 二.MAVEN下载与安装 下载地址:http://maven.apache.org/ ...

  3. 【托业】【新东方托业全真模拟】TEST05~06-----P5~6

    credit A with B 把A归功于B present A with B 给A赠送B proofread thoroughly 彻底地校对:exclusively 专门地:独占地:apparen ...

  4. vue项目搭建步骤

    https://blog.csdn.net/echo008/article/details/77099058 https://blog.csdn.net/echo008/article/details ...

  5. 问题: 揭秘Angualr2 书上问卷调查

    npm install 初夏下面问题: 0 info it worked if it ends with ok1 verbose cli [ '/home/linux_ubuntu164/tools/ ...

  6. java求最大公约数,和最小公倍数

    import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner sc = ...

  7. 蓝桥杯近三年初赛题之一(15年b组)

    临近比赛,自己定时做了近三年的初赛题,不是很理想,10道题平均做对5+道.为了这次比赛,总共做了200题左右吧,估计去北京参加决赛有点难,不过不管怎样,对得起自己万余行代码就好. 一.15年初赛题(第 ...

  8. 将指定世界中的指定位置的Block转化为箱子

    在bukkit中,block可以操作所有的三位像素方块,如果是向对block进一步操作,我们就需要得到BlockState, BlockState表示一个方块的状态,才能够对方块进行位置等状态的操作, ...

  9. IRC 打字交流

    kali 里面用 apt-get install weechat 安装完成后,输入 weechat 命令就能启动客户端了 要想使用 IRC,就需要先连接一个 irc 服务器,选择了大名鼎鼎的 chat ...

  10. CentOS7+Apache+MySQL+PHP环境

    Apache 1.安装Apache:yum -y install httpd 2.开启apache服务:systemctl start httpd.service 3.设置apache服务开机启动:s ...