Java语言JDBC数据库

来源:互联网 发布:中金数据 光环新网 编辑:程序博客网 时间:2024/06/05 09:26
  1. public class MyJDBC {  
  2.   
  3.     public static void main(String[] args) 
  4.     {  
  5.   
  6.   
  7.         // 数据库JDBC驱动地址  
  8.         String driverManageString = null;  
  9.         // 数据库连接地址  
  10.         String url = null;  
  11.         // 数据连接密码  
  12.         String password = null;  
  13.         // 数据库连接用户名  
  14.         String user = null;  
  15.           
  16.         try {  
  17.               
  18.               
  19.             // 加载数据库JDBC连接恭驱动  
  20.             Class.forName(driverManageString);  
  21.               
  22.               
  23.               
  24.             // 创建数据库连接  
  25.             Connection connection = DriverManager.getConnection(url, user, password);  
  26.               
  27.          // 创建一个执行SQL语句的工具接口  
  28.             Statement stmt = connection.createStatement();  
  29.               
  30.             ResultSet rs = stmt.executeQuery(" select id, name, pwd from custmer");  
  31.               
  32.             //获取查询出的数据  
  33.             while (rs.next()) {  
  34.                   
  35.                 System.out.println(rs.getObject(1));  
  36.                   
  37.             }  
  38.               
  39.             // 创建一个预编译的SQL语句工具接口  
  40.             PreparedStatement pstmt = connection.prepareStatement(" select id, name, pwd from custmer where id = ?");  
  41.             pstmt.setObject(0new Object());  
  42.   
  43.             // 结果集,返回SQL查询后生成的一张数据表  
  44.             ResultSet prs = pstmt.executeQuery();  
  45.               
  46.             while (prs.next()) {  
  47.                   
  48.                 System.out.println(rs.getObject(1));  
  49.                   
  50.             }  
  51.               
  52.             connection.close();  
  53.               
  54.             rs = null;  
  55.               
  56.             prs = null;  
  57.               
  58.         }  
  59.         catch (ClassNotFoundException e) 
  60. {  
  61.               
  62.             e.printStackTrace();  
  63.         }  
  64.         catch (SQLException e) 
  65. {  
  66.   
  67.             e.printStackTrace();  
  68.         }  
  69.   
  70.     }    
  71. }  
0 0
原创粉丝点击