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
  • 相关阅读:
    django之分页
    linux后台运行和关闭、查看后台任务
    Django的模板系统
    Django的视图系统
    Django的配置文件(settings.py)
    Django的URL路由
    初始Django
    shell if判断总结
    一个抓取智联招聘数据并存入表格的python爬虫
    Python MySQLdb 查询中文出现问号的解决方法
  • 原文地址:https://www.cnblogs.com/thlzhf/p/3941776.html
Copyright © 2011-2022 走看看