package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class BaseDao { private String driver = "com.mysql.jdbc.Driver"; private String db_URL = "jdbc:mysql://localhost:3306/netorder"; private String username = "root"; private String password = "*******"; private Connection conn = null; public void openConnection() { try { Class.forName(driver); conn = DriverManager.getConnection(db_URL,username,password); } catch(Exception e) { e.printStackTrace(); } } public int executeUpdate(String sql,Object[] objs) { int res = -1; try { PreparedStatement pst = conn.prepareStatement(sql); if(objs != null) { for(int i = 0; i < objs.length; i++) { pst.setObject(i + 1, objs[i]); } } res = pst.executeUpdate(); } catch(Exception e) { e.printStackTrace(); } return res; } public ResultSet executeQuery(String sql,Object[] objs) { ResultSet rs = null; try { PreparedStatement pst = conn.prepareStatement(sql); if(objs != null) { for(int i = 0; i < objs.length; i++) { pst.setObject(i + 1, objs[i]); } } rs = pst.executeQuery(); } catch(Exception e) { e.printStackTrace(); } return rs; } public void close() { try { conn.close(); } catch(Exception e) { e.printStackTrace(); } } }
使用方法:以user表为例
1.让UserDao继承BaseDao
2.openConnection();//实例化数据库连接
3.执行executeQuery()实现查询或者执行excuteUpdate实现增删改
4.close();//关闭数据库连接
PS:支持预处理,可在sql字符串中加入?表示待定,使用例子如下:
public boolean checkUser(String username,String password) { openConnection(); String sql = "select id from user where username = ? and password = ?"; Object[] objs = new Object[]{username,password}; ResultSet rs = executeQuery(sql, objs); close(); if(rs != null) return true; else return false; }