zoukankan      html  css  js  c++  java
  • Java Web整合开发(12) -- JDBC

    JDBC访问数据库的一般步骤:

    注册驱动,获取连接,获取Statement,执行SQL并返回结果集,遍历结果集显示数据,释放连接。

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    
    try{
        // 注册 MySQL 驱动. 也可以使用下面两种方式的任一种
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        //new com.mysql.jdbc.Driver();
        //Class.forName("com.mysql.jdbc.Driver").newInstance();
        
        // 获取数据库连接。 三个参数分别为 连接URL,用户名,密码
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databaseWeb", "root", "mysql");
        
        // 获取 Statement。 Statement 对象用于执行 SQL。相当于控制台。
        stmt = conn.createStatement();
        
        // 使用 Statement 执行 SELECT 语句。返回结果集。
        rs = stmt.executeQuery("select * from tb_person");
        while (rs.next()) {
            out.println("...");
        }
    }catch(SQLException e){
        out.println("发生了异常:" + e.getMessage());
        e.printStackTrace();
    }finally{
        // 关闭
        if(rs != null)
          rs.close();
        if(stmt != null)
          stmt.close();
        if(conn != null)
          conn.close();
    }

    常见的数据库连接:

    MySQL:          jdbc:mysql://localhost:3306/db
    Oracle:          jdbc:oracle:thin:@localhost:1521/db
    DB2:            jdbc:db2://localhost:6789/db
    PostgreSQl:     jdbc:postgresql://localhost:5432/db
    Sybase:jdbc:     jtds:sybase://localhost:2638/db
    SQLServer:      jdbc:microsoft:sqlserver://localhost:1433;databaseName=db
    SQLServer 2005: jdbc:sqlserver://localhost:1433;databaseName=db
  • 相关阅读:
    CSS基础学习(二)
    CSS基础学习(一)
    《人月神话》读后感(第五六章)
    Python基础学习
    团队项目介绍
    全国疫情数据可视化展示(详细介绍)
    《人月神话》读后感(第三四章)
    拓展欧几里德
    Siano
    操作系统内存大页(THP)对redis性能的影响
  • 原文地址:https://www.cnblogs.com/thlzhf/p/3941776.html
Copyright © 2011-2022 走看看