- 通过编写数据库工具类,将数据库的连接、查询、更新操作编写成特定的方法;
- 使用PreparedStatement语句;
- 传递数组形成SQL语句;
public class DBUtil {
private static Connection conn;
private static PreparedStatement ps;
private static ResultSet rs;
public static Connection getConnection(){
String Url = "jdbc:mysql://localhost:3306/smp";
String User = "root";
String Passwd = "123123";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(Url, User, Passwd);
return conn;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static ResultSet excuteQuery(String sql){
if (getConnection() == null) {
return null;
}
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public static ResultSet excuteQuery(String sql,Object[] obj){
if (getConnection() == null) {
return null;
}
try {
ps = conn.prepareStatement(sql);
for (int i = 0; i <obj.length ; i++) {
ps.setObject(i+1,obj[i]);
}
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public static int executeUpdate(String sql) {
int result = -1;
if (getConn() == null) {
return result;
}
try {
ps = conn.prepareStatement(sql);
result = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public static int excuteUpdate(String sql,Object[] obj){
int result = -1;
if (getConnection() == null) {
return 0;
}
try {
ps = conn.prepareStatement(sql);
for (int i = 0; i <obj.length ; i++) {
ps.setObject(i+1,obj[i]);
}
result = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public static void DBclose(){
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
传递一个参数:
public Student queryNumber(String number) throws SQLException{
Student stu = null;
String sql = "SELECT * from student WHERE Stu_number = ? ";
Object[] param ={number};
ResultSet rs = DBUtil.excuteQuery(sql,param);
while (rs.next()){
stu = new Student(rs.getString("Stu_name"),rs.getString("Stu_number"));
stu.setId(rs.getInt("Stu_id"));
stu.setNotes(rs.getString("Stu_notes"));
stu.setBirthday(rs.getString("Stu_birthday"));
stu.setSex(rs.getString("Stu_sex"));
}
DBUtil.DBclose();
System.out.println(stu.toString());
传递多个参数:
public Student queryNumber(String number,String id) throws SQLException{
String sql = "SELECT * from student WHERE Stu_number = ? OR id = ?";
Object[] param ={number,id};
ResultSet rs = DBUtil.excuteQuery(sql,param);