本文概览:描述了通过JDBC最原始方法访问mysql。还讨论了一个问题:一个stament是否可以执行多次sql.
1 一个实例
如下一个函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
public void select() { Connection ct = null; Statement st = null; ResultSet rs = null; // 1.执行一个sql的四部曲 try { // 1.1加载驱动 Class.forName("org.gjt.mm.mysql.Driver"); // 1.2 获取连接 ct = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "53061208"); // 1.3 获取statement st = ct.createStatement(); String sql = "select * from student where id = 1"; // 1.4 执行stamemt rs = st.executeQuery(sql); while (rs.next()) { System.out.println(rs.getString("id") + " "); System.out.print(rs.getString("name") + " "); } } catch ( Exception e1) { e1.printStackTrace(); } finally { //2关闭数据库链接ct,st,rs try { if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (ct != null) { ct.close(); } } catch (Exception ex) { } } } |
2 一个问题
一个stament是否可以执行多次sql?
答案是可以。如下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
public class StudentDaoWithJdbc { /** * 使用一个statement执行多个sql */ public void excuteSqlsWithOneStatment() { Connection ct = null; Statement st = null; ResultSet rs = null; //1.构建数据库链接三部曲 try { Class.forName("org.gjt.mm.mysql.Driver"); ct = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "53061208"); st = ct.createStatement(); String sql1 = "select * from student where id = 1"; String sql2 = "select * from student where id = 2"; queryWithStatement(st, sql1); queryWithStatement(st, sql2); } catch ( Exception e1) { e1.printStackTrace(); } finally { //2关闭数据库链接ct,st,rs try { if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (ct != null) { ct.close(); } } catch (Exception ex) { } } } private void queryWithStatement(Statement st, String sql) { ResultSet rs = null; try { rs = st.executeQuery(sql); while (rs.next()) { System.out.print(rs.getString("id") + " "); System.out.println(rs.getString("name") + " "); } } catch (Exception e) { } finally { try { rs.close(); } catch (Exception e) { } } } } |