对于jdbc有很多常用的操作,例如数据库的增删改查,代码如下:
package mysql_jdbc;
/**
* @author Hercules
* @version 创建时间:2020年6月13日 上午9:44:34
* JDBC的一个工具类,封装常用的增删改查的操作。
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Driver;
public class SqlUtils {
//其实在写的这个工具类中,驱动只需要加载一次
static {
/**
* 正常情况下驱动一个项目只需要加载一次即可
*/
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取数据库链接
* @return
*/
public static Connection getConnection() {
try {
return DriverManager.getConnection("jdbc:mysql:///test","root","root");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 关闭资源
* @param rs
* @param pst
* @param conn
*/
public static void close(ResultSet rs,PreparedStatement pst,Connection conn) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pst!=null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 增删改的操作
* @param sql sql语句
* @param params sql执行所需要的参数
* Object...称为可变参数
* 当我们调用update的时候
* update("sql")
* update("sql",1)
* update("sql",1,2)
* 上述三种情况均可以调用这个函数,而且不会报错
* 当我们在函数的参数中放入可变参数的时候
* 可变参数必须要放在参数列表的最后,要不然就没有办法识别了
* @return
*/
public static int update(String sql,Object...params) {
System.out.println(params.length);
return 0;
}
public static void main(String[] args) {
update("");
}
}
这里注意main函数中的参数,只有一个""。那这个时候可变参数的长度为0,
执行代码结果如下:
假如这里把main函数中的update改为:
update("",1);
而后输出可变参数的长度为1:
而后这里还要利用反射完成完整的工具类:这里涉及到以后要学习的框架的内容,先自己写出来,以后再学的时候就比较好理解了。
package mysql_jdbc;
/**
* @author Hercules
* @version 创建时间:2020年6月15日 下午7:40:49
* 类说明
*/
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class SqlUtils4 {
/**
* 静态块,负责加载驱动,驱动一般只加载一次
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获得链接
* @return
*/
public static Connection getConnection() {
try {
return DriverManager.getConnection("jdbc:mysql:///test","root","root");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 关闭资源
* @param rs
* @param pst
* @param conn
*/
public static void close(ResultSet rs,PreparedStatement pst,Connection conn) {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 增删改数据
* @param sql
* @param params
* @return
* @throws SQLException
*/
public static int update(String sql,Object...params) throws SQLException {
Connection conn = getConnection();
PreparedStatement pst = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pst.setObject(i+1, params[i]);
}
int result = pst.executeUpdate();
close(null, pst, conn);
return result;
}
/**
* 返回查询结果
* @param <T>
* @param clazz
* @param sql
* @param params
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
public static <T> List<T> select(Class<T> clazz,String sql,Object...params) throws SQLException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, NoSuchFieldException, IllegalArgumentException, InvocationTargetException{
Connection conn = getConnection();
PreparedStatement pst = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pst.setObject(i+1, params[i]);
}
ResultSet rs = pst.executeQuery();
List<T> list = resolveResultSet(clazz, rs);
return list;
}
/**
* 只筛选出一条数据
* @param <T>
* @param clazz
* @param sql
* @param params
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws SQLException
*/
public static <T> T selctOne(Class<T> clazz,String sql,Object...params) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, NoSuchFieldException, IllegalArgumentException, InvocationTargetException, SQLException {
return select(clazz, sql, params).get(0);
}
/**
* 获取结果集
* @param <T>
* @param clazz
* @param rs
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
public static <T> List<T> resolveResultSet(Class<T> clazz,ResultSet rs) throws SQLException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, NoSuchFieldException, IllegalArgumentException, InvocationTargetException{
List<T> list = new ArrayList<T>();
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()) {
T t = clazz.newInstance();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String columnName = rsmd.getColumnName(i);
Object columnValue = rs.getObject(columnName);
String first = columnName.charAt(0)+"";
String methodName = "set"+first.toUpperCase()+columnName.substring(1);
Method method = clazz.getDeclaredMethod(methodName, clazz.getDeclaredField(columnName).getType());
method.invoke(t, columnValue);
}
list.add(t);
}
return list;
}
/**
* 更新对象操作
* @param obj
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws SQLException
*/
public static int update(Object obj) throws IllegalArgumentException, IllegalAccessException, SQLException {
//重点在于拼接语句 update 表名 set 字段1=值1,字段2=值2,where 主键 = 值
//这里约定主键是以id结尾的,实际的一些工具类中判断主键的方法更加的复杂,这里暂时作此约束
Class clazz = obj.getClass();
StringBuilder sql = new StringBuilder();
List<Object> list = new ArrayList<Object>();
Field[] fields = clazz.getDeclaredFields();
Field primaryKey = null;
sql.append("update ");
sql.append(clazz.getSimpleName());
sql.append(" set ");
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
if(field.getName().endsWith("id")) {
primaryKey = field;
}
if(field.get(obj) != null && !field.getName().endsWith("id")) {
sql.append(field.getName());
sql.append("=");
sql.append("?");
list.add(field.get(obj));
if(i != fields.length-1) {
sql.append(",");
}
}
}
list.add(primaryKey.get(obj));
sql.append(" where ");
sql.append(primaryKey.getName());
sql.append("=");
sql.append("?");
int result = update(sql.toString(), list.toArray());
return result;
}
/**
* 插入对象的操作
* @param obj
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws SQLException
*/
public static int insert(Object obj) throws IllegalArgumentException, IllegalAccessException, SQLException {
//重点在于拼接语句 insert intio 表名 (字段1,字段2,字段3,字段4) values (?,?,?,?)
Class clazz = obj.getClass();
StringBuilder sql = new StringBuilder();
StringBuilder param = new StringBuilder();
List<Object> params = new ArrayList<Object>();
sql.append("insert into ");
sql.append(clazz.getSimpleName()+" (");
param.append(" values (");
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
if(field != null) {
params.add(field.get(obj));
sql.append(field.getName());
param.append("?");
}
if(i != fields.length - 1) {
sql.append(",");
param.append(",");
}
}
sql.append(") ");
param.append(")");
sql.append(param);
return update(sql.toString(), params.toArray());
}
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, SQLException {
User user = new User();
user.setUsernameid("无敌");
user.setPower(6);
// try {
// System.out.println(insert(user));
// } catch (IllegalArgumentException | IllegalAccessException | SQLException e) {
// e.printStackTrace();
// }
System.out.println(update(user));
}
}