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 | [code=java] package com.sn.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DemoWork { public static void main(String[] args) throws SQLException { Connection con = null ; //定义 Statement st = null ; ResultSet rs = null ; try { /** * 准备四大参数 */ String driverClassName = "com.mysql.jdbc.Driver" ; String url = "jdbc:mysql://localhost:3306/person" ; String username = "root" ; String password = "123" ; Class.forName(driverClassName); //加载驱动 con = DriverManager.getConnection(url, username, password); //实例化 st = con.createStatement(); //创建Statement String selectConnection = "select * from tb_emp" ; //查询数据库表中的数据 rs = st.executeQuery(selectConnection); //进行遍历 while (rs.next()){ //判断是否有下一行 System.out.println(rs.getString( "name" ) + "," + rs.getString( "sex" ) + "," + rs.getInt( "age" ) + "," + rs.getString( "address" )); } } catch (Exception e) { throw new RuntimeException(e); //处理异常 } finally { //反向关闭资源 if (rs != null ){ rs.close(); } if (st != null ){ st.close(); } if (con != null ){ con.close(); } } } } |
JDBC连接MySQL之查询数据(代码规范化)
最新推荐文章于 2024-03-28 16:29:26 发布