zoukankan      html  css  js  c++  java
  • JDBC的配置及使用入门

    JDBC本质上一套规范接口,建立java和数据库的连接,从而对数据库进行CRUD,下面以mysql数据库为例,如图:

    JDBC的代码实现:

     1 package JdbcUtil;
     2 
     3 ;
     4 
     5 /**
     6  * @author o_0sky
     7  * @date 2019/2/18 1:57
     8  */
     9 public class Standard {
    10     //获取连接
    11     Connection con = null;
    12     //创建statement对象
    13     Statement statement = null;
    14     ResultSet resultSet = null;
    15     //注册mysql驱动
    16      try{Class.forName("com.mysql.jdbc.Driver");
    17     //配置数据库参数
    18     String url = "jdbc:mysql://localhost:3306/test";
    19     String username = "root";
    20     String password = "root";
    21     con=DriverManager.getConnection(url,username,password);
    22     statement=con.createStatement();
    23     //发送并执行sql
    24     String sql = "select * from tb_user";
    25     resultSet=statement.executeQuery(sql);
    26     while(resultSet.next())
    27     {
    28         String name = resultSet.getString("name");
    29         String age = resultSet.getString("age");
    30         System.out.println(name);
    31         System.out.println(age);
    32     }}
    33     catch(Exception e){
    34          e.getStackTrace();
    35     }
    36     //释放资源
    37     finally{
    38          if (resultSet!=null){
    39              try {
    40                  resultSet.close();
    41              } catch (Exception e1) {
    42                  e1.printStackTrace();
    43              }
    44          }
    45          if (statement!=null){
    46              try {
    47                  statement.close();
    48              } catch (Exception e1) {
    49                  e1.printStackTrace();
    50              }
    51          }
    52          if (con!=null){
    53              try {
    54                  con.close();
    55              } catch (Exception e1) {
    56                  e1.printStackTrace();
    57              }
    58          }
    59     }
    60 
    61 
    62 }
  • 相关阅读:
    在Centos 7下编译openwrt+njit-client
    开博随笔
    Chapter 6. Statements
    Chapter 4. Arrays and Pointers
    Chapter 3. Library Types
    Chapter 2.  Variables and Basic Types
    关于stm32不常用的中断,如何添加, 比如timer10 timer11等
    keil 报错 expected an identifier
    案例分析 串口的地不要接到电源上 会烧掉
    案例分析 CAN OPEN 调试记录 进度
  • 原文地址:https://www.cnblogs.com/linsky/p/10393611.html
Copyright © 2011-2022 走看看