• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
milkjack
博客园    首页    新随笔    联系   管理    订阅  订阅
关于java后台数据库的连接(增删改查)的方法集合

Connection conn=null;
PreparedStatement pst=null;
ResultSet rs=null;

//连接数据库
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");

conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/monkeye?useUnicode=true&characterEncoding=UTF-8", "root", "123456");

//?后面可以加上编码格式,设置setUnicode=true&characterEncoding=UTF-8

}catch(Exception e){
e.printStackTrace();
}
return conn;
}

//关闭数据库的连接
public void getClose(ResultSet rs,PreparedStatement pst,Connection conn) {
try {
if(rs!=null)rs.close();
if(pst!=null)pst.close();
if(conn!=null)conn.close();
}catch(Exception e) {
e.printStackTrace();
}
}

//数据库的增删改方法集合
public boolean getUpdate(String sql,List<Object> list) {
try {
pst=getConnection().prepareStatement(sql);
if(list.size()>0) {
for(int i=0;i<list.size();i++) {
pst.setObject(i+1, list.get(i));//pst从下标1开始,list从下标0开始
}
}
int num=pst.executeUpdate();
if(num>0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}

//数据库的查询方式集合
public <T>List<T> getQuery(String sql,List<Object> list,Class clazz){
List<T> li=new ArrayList<T>();
try {
pst=getConnection().prepareStatement(sql);
if(list.size()>0) {
for(int i=0;i<list.size();i++) {
pst.setObject(i+1, list.get(i));
}
}
rs=pst.executeQuery();
ResultSetMetaData rsm=rs.getMetaData();
int column=rsm.getColumnCount();
while(rs.next()) {
Object obj=clazz.newInstance();
for(int i=1;i<=column;i++) {
String name=rsm.getColumnName(i);
Object o=rs.getObject(i);
Field f=clazz.getDeclaredField(name);   //通过名字映射获取属性
f.setAccessible(true);
f.set(obj, o);  //将属性o赋给obj对象
}
li.add((T)obj);
}
} catch (Exception e) {
e.printStackTrace();
}
return li;
}

posted on 2018-05-30 18:53  milkjack  阅读(2440)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3