idea连接mysql并增删改查,idea连接数据库(增删改查)通⽤
⽅法
//1、多条查询⽅法
public class TestCrud {
public static void main(String[] args) {
String sql="select*from stus";
List users = TestCrud.queryOne(User.class, sql);
System.out.String());
}
public static List queryOne(Class clazz, String sql, ags) {
Connection connection = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
//1:连接数据库(我这边调⽤的是⽅法)
connection = Conn();
//2:预编译
pst = connection.prepareStatement(sql);
//3:填充占位符
for (int i = 0; i < ags.length; i++) {
pst.setObject((i + i), ags[i]);
}
/
/4执⾏操作
rs = uteQuery();
//5:判断是否有值,然后打印
//创建⼀个元数据类型接收返回值
ResultSetMetaData metaData = rs.getMetaData();
//获取表中具体的列数
int count = ColumnCount();
List list = new ArrayList();
while (rs.next()) {
T t = wInstance();
for (int i = 0; i < count; i++) {
/
/获取对应的字段值
Object value = rs.getObject((i + 1));
//获取到对应字段的别名
String label = ColumnLabel((i + 1));
//获取到对应的字段
Field field = DeclaredField(label);
//设置可以⾃⼰设置的权限
field.setAccessible(true);
//将值装配对象
field.set(t,value);
}
list.add(t);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭流(通⽤的⽅法)
JDBCutil.closeResourse2(rs,pst,connection);
}
return null;
}
}
//查询单条的⽅法
mysql数据库的方法
// public static T queryOne(Classclazz, String sql, args) { // Connection connection = null;
// PreparedStatement pstm = null;
// ResultSet rs = null;
// //连接数据库
// connection = Conn();
// try {
// pstm = connection.prepareStatement(sql);
// for (int i = 0; i < args.length; i++) {
// pstm.setObject((i + 1), args[i]);
/
/ }
// rs = uteQuery();
// ResultSetMetaData metaData = rs.getMetaData(); // int columnCount = ColumnCount(); // T t = wInstance();
// if (rs.next()) {
// for (int i = 0; i < columnCount; i++) {
// Object value = rs.getObject((i + 1));
// String label = ColumnLabel((i + 1)); // Field declaredField = DeclaredField(label); // declaredField.setAccessible(true);
// declaredField.set(t, value);
// }
// return t;
// }
// } catch (Exception e) {
// e.printStackTrace();
// }finally {
// JDBCutil.closeResourse2(rs,pstm,connection);
// }
// return null;
// }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。