JDBC的操作步骤 (2)

查询

public class DQLTest { @Test public void testQuerySigle() throws Exception { String sql = "SELECT * FROM s_student WHERE id = 1"; //加载驱动 Class.forName("com.mysql.jdbc.Driver"); //获取连接对象 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "admin"); //获取语句对象 Statement st = conn.createStatement(); //执行sql语句 ResultSet rs = st.executeQuery(sql); if(rs.next()){ long id = rs.getLong("id"); long age = rs.getLong("age"); String name = rs.getString("name"); System.out.println(id + "," + age +"," + name); } rs.close(); st.close(); conn.close(); } @Test public void testAll() throws Exception { String sql = "SELECT * FROM s_student"; Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","admin"); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()){ String name = rs.getString("name"); long id = rs.getLong("id"); long age = rs.getLong("age"); System.out.println(name + "," + id +"," + age); } rs.close(); st.close(); conn.close(); } }

五、总结

JDBC的CUID操作就是严格按照上述步骤完成的,可以发现基本操作都很相同,也很容易理解。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpgfxj.html