(笔记)数据库查询操作

来源:互联网 发布:马云 膨胀 知乎 编辑:程序博客网 时间:2024/04/30 03:41
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import student.Student;import connection.DBConnection;public class DBUtil {public static List<Map> executeStudents() throws Exception{ PreparedStatement pst = null; ResultSet rs = null; Connection conn = DBConnection.getConnection(); String sql = "select * from student"; List<Map> list = new ArrayList<Map>(); pst = conn.prepareStatement(sql); rs = pst.executeQuery(); while(rs.next()){ Map map = new HashMap(); map.put("name",rs.getString("name")); map.put("age",rs.getInt("age")); map.put("sex",rs.getInt("sex")); map.put("birthday",rs.getString("birthday")); map.put("major",rs.getString("major")); list.add(map); } rs.close(); pst.close(); return list; }public static int addStudent(Student student) throws Exception{ PreparedStatement pst = null; Connection conn = DBConnection.getConnection(); String sql = "insert into student values('" + student.getName() + "'," + student.getAge() + "," + student.getSex() + ",'" + student.getBirthday() + "','" + student.getMajor() + "');"; pst = conn.prepareStatement(sql); int affect = pst.executeUpdate(); pst.close(); return affect; }}
0 0