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();
        }
    }

}

}

原文地址:https://www.cnblogs.com/chen991126/p/13956160.html