JDBC 01: 建立与数据库的连接

示例:
建立与数据库"web01"的连接, 并查询输出"user"表中所有的数据

package
com.Jasper2003.jdbc01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCDemo01 { public static void main(String[] args) { Connection con = null; Statement stmt = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); // 使用什么驱动连接数据库 String url = "jdbc:mysql://localhost:3306/web01?useUnicode=true&characterEncoding=UTF8&useSSL=false"; String user = "root"; String password = "root"; con = DriverManager.getConnection(url,user,password); stmt = con.createStatement(); rs = stmt.executeQuery("select * from user"); while(rs.next()) { // 获取数据的第一种方式: 列数 System.out.println(rs.getInt(1)+","+rs.getString(2)+","+rs.getString(3)); // 获取数据的第二种方式: 列名 System.out.println(rs.getInt("id")+","+rs.getString("username")+","+rs.getString("password")); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(rs!=null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(stmt!=null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(con!=null) con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }

输出:

 

posted @ 2020-08-21 02:59  Jasper2003  阅读(112)  评论(0编辑  收藏  举报