普通操作
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class demo { public static void main(String[] args) { //jdbd:mysql://地址:端口/数据库名?是否使用Unicode&编码格式&时区 String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai"; //用户名 String user = "root"; //密码 String password = "123456"; Connection con = null; Statement stm = null; List<Student> list = new ArrayList<Student>(); try { //建立连接 con = DriverManager.getConnection(url,user,password); //准备好数据传输对象 stm = con.createStatement(); //发送查询语句 ResultSet rs = stm.executeQuery("select * from student where name = '游文智'"); while (rs.next()) { //接受数据 Student st = new Student(rs.getString("name"), rs.getInt("id"), rs.getString("sno")); list.add(st); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { //关闭流 stm.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } list.forEach(i->{ System.out.println(i); }); } }
预加载操作
public List<Double> query(String name) { // TODO Auto-generated method stub //SQL语句 String sql = "SELECT point FROM student a,score b\r\n" + "WHERE a.sno = b.sno AND a.`name` = ?"; List<Double> list = new ArrayList<Double>(); PreparedStatement pstm = null; try { //预加载SQL语句 pstm = getCon().prepareStatement(sql); //加载问号的值 pstm.setString(1, name); ResultSet rs = pstm.executeQuery(); while (rs.next()) { Double d = rs.getDouble("point"); list.add(d); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; }