zoukankan      html  css  js  c++  java
  • JDBC连接数据库

    1.使用JDBC API 连接和访问数据库,一般分为以下5个步骤

    (1)加载驱动程序

    (2)建立连接对象

    (3)创建语句对象

    (4)获得SQL语句的执行结果

    (5)关闭建立的对象,释放资源
    数据库进行增删改查操作。
    操作步骤一共分为以下七步:加载驱动、创建连接、写一个 sql 语句、预编译 sql 语句、执行 sql语句、获得结果、处理结果、关闭所有连接。
    代码如下

    package sql;

    import java.sql.*;

    public class Test1 {
    public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

        try {
            // 加载驱动类
            Class.forName("com.mysql.jdbc.Driver");
            long start = System.currentTimeMillis();
    
            // 建立连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
                    "root", "yyy123654");
            long end = System.currentTimeMillis();
            System.out.println(conn);
            System.out.println("建立连接耗时: " + (end - start) + "ms 毫秒");
    
            // 创建Statement对象
            stmt = conn.createStatement();
    
            // 执行SQL语句
            rs = stmt.executeQuery("select * from heima");
            System.out.println("id\tname\tage\tsex");
            while (rs.next()) {
                System.out.println(rs.getInt(1) + "\t" + rs.getString(2)
                        + "\t" + rs.getInt(3) + "\t" + rs.getInt(4));
            }
    
    
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
    
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
    }
    

    }

  • 相关阅读:
    idea 中使用 svn
    [剑指offer] 40. 数组中只出现一次的数字
    [剑指offer] 39. 平衡二叉树
    [剑指offer] 38. 二叉树的深度
    [剑指offer] 37. 数字在排序数组中出现的次数
    [剑指offer] 36. 两个链表的第一个公共结点
    [剑指offer] 35. 数组中的逆序对
    vscode在win10 / linux下的.vscode文件夹的配置 (c++/c)
    [剑指offer] 34. 第一个只出现一次的字符
    [剑指offer] 33. 丑数
  • 原文地址:https://www.cnblogs.com/chen991126/p/13956160.html
Copyright © 2011-2022 走看看