zoukankan      html  css  js  c++  java
  • JDBC 查询 模板

    JDBC 查询 与增删改不同的是SQL语句的不同,还有查询反回的是结果集  需要定义 

    利用 next()方法逐层查询数据

    使用getXXX方法获取数据

    代码相关参数根据个人设置进行修改!!!!

     1 package project;
     2 /**
     3  * JDBC 查询
     4  * 
     5  */
     6 import java.sql.Connection;
     7 import java.sql.DriverManager;
     8 import java.sql.ResultSet;
     9 import java.sql.SQLException;
    10 import java.sql.Statement;
    11 import java.util.Properties;
    12 
    13 public class jdbc2 {
    14     
    15     public static void main(String[] args)  {
    16         Connection connection = null;
    17         Statement stmt= null;
    18         ResultSet rs = null; // 定义反回的结果集
    19         try {
    20         final String URL ="jdbc:mysql://localhost:3306/onlinedb?serverTimezone=UTC&characterEncoding=utf-8" ;
    21          final  String USERNAME ="root";
    22          final String PWD="979416";
    23         //导入驱动加载具体的驱动类
    24         Class.forName("com.mysql.cj.jdbc.Driver");
    25             Properties info;
    26         //与数据库建立连接
    27          connection = DriverManager.getConnection(URL, USERNAME, PWD);
    28             //发送sql语句,执行命令
    29              stmt=connection.createStatement();
    30             
    31              String sql = "select infoid,infoname from info";    //执行查询命令             
    32             //执行sql
    33              rs = stmt.executeQuery(sql);
    34             //处理结果
    35              while(rs.next()) {              //使用 next()方法 循环得到数据库的数据
    36                  
    37                 int id = rs.getInt("infoid");         //获取 int数据
    38                 String name = rs.getString("infoname");   //获取String数据
    39                 System.out.println(id+"---"+name);
    40              }
    41              
    42             
    43             
    44         }catch (ClassNotFoundException e) {           // 分层处理异常 
    45             e.printStackTrace();
    46         }catch(SQLException e) {
    47             e.printStackTrace();
    48         }catch(Exception e) {
    49             e.printStackTrace();
    50         }finally {
    51             try {
    52             if(rs!=null) rs.close();            //关闭!     规则 先开后关 后开先关
    53             if(stmt!=null)stmt.close();
    54             
    55             if(connection!=null)connection.close();
    56             }catch(SQLException e) {
    57                 e.printStackTrace();
    58             }
    59         }
    60             
    61             
    62         
    63     }
    64      
    65     
    66     
    67     
    68 }
  • 相关阅读:
    OS X EI Capitan 安装mysql-5.7.9
    CAS SSO
    单点登录SSO
    videojs 视频开发API
    NodeJS无所不能:细数10个令人惊讶的NodeJS开源项目
    程序员使用Node的十个技巧
    pdf 回退快捷键
    公式神器 Mathpix Snip 比mathtype快
    AI studio 尝试
    tmux 使用
  • 原文地址:https://www.cnblogs.com/-xsw000/p/12535058.html
Copyright © 2011-2022 走看看