Java基础回顾系列-数据库编程

版权声明:不存在一劳永逸的技术 只存在不断学习的人。本文为博主原创文章,未经博主允许不得转载。交流联系QQ:1120121072 https://blog.csdn.net/u013474568/article/details/86084938

数据库简介

针对Java数据库开发的包都在java.sql包下。都是些比较基础的。
详细参见:https://docs.oracle.com/en/java/javase/11/docs/api/java.sql/java/sql/package-summary.html

工具包

java.sql API 内容

与数据库建立连接

  • DriverManager class - 与驱动程序建立连接
  • SQLPermission class - 在安全管理器(例如applet)中运行的代码尝试通过安装程序设置日志记录流时提供权限 DriverManager
  • Driverinterface - 提供基于JDBC技术注册和连接驱动程序的API(“JDBC驱动程序”); 通常只由DriverManager班级使用
  • DriverPropertyInfoclass - 提供JDBC驱动程序的属性; 一般用户不使用

执行SQL语句数据库

  • Statement - 用于发送基本的SQL语句
  • PreparedStatement- 用于发送预准备语句或基本SQL语句(派生自Statement)
  • CallableStatement- 用于调用数据库存储过程(派生自PreparedStatement)
  • Connection interface - 提供创建语句和管理连接及其属性的方法
  • Savepoint - 在事务中提供保存点

检索和更新查询结果

  • ResultSet 接口

SQL类型对应Java类型映射

  • Array 接口 - SQL的映射 ARRAY
  • Blob 接口 - SQL的映射 BLOB
  • Clob 接口 - SQL的映射 CLOB
  • Date class - SQL的映射 DATE:java.util.Date转换java.sql.Date
  • NClob 接口 - SQL的映射 NCLOB
  • Ref 接口 - SQL的映射 REF
  • RowId 接口 - SQL的映射 ROWID
  • Struct 接口 - SQL的映射 STRUCT
  • SQLXML 接口 - SQL的映射 XML
  • Time 类 - SQL的映射 TIME
  • Timestamp 类 - SQL的映射 TIMESTAMP
  • Types 类 - 为SQL类型提供常量

元数据

  • DatabaseMetaData interface - 提供有关数据库的信息
  • ResultSetMetaDatainterface - 提供有关ResultSet对象 列的信息
  • ParameterMetaDatainterface - 提供有关PreparedStatement命令 参数的信息

异常

  • SQLException - 当访问数据时出于问题而被大多数方法抛出,而出于其他原因则由某些方法抛出
  • SQLWarning - 抛出以表示警告
  • DataTruncation - 抛出表示数据可能已被截断
  • BatchUpdateException - 抛出表示批量更新中的所有命令都未成功执行

API方法

DriverManager

public static Connection getConnection​(String url, String user, String password) throws SQLException

Connection

Statement createStatement() throws SQLException
PreparedStatement prepareStatement​(String sql) throws SQLException
CallableStatement prepareCall​(String sql) throws SQLException

void setAutoCommit​(boolean autoCommit) throws SQLException
void setTransactionIsolation​(int level) throws SQLException
void commit() throws SQLException
void rollback() throws SQLException
void close() throws SQLException

Statement

int executeUpdate​(String sql) throws SQLException
ResultSet executeQuery​(String sql) throws SQLException

PreparedStatement

void setString​(int parameterIndex, String x) throws SQLException
void setInt​(int parameterIndex, int x) throws SQLException
void setTime​(int parameterIndex, Time x) throws SQLException
void setClob​(int parameterIndex, Reader reader) throws SQLException

ResultSet executeQuery() throws SQLException
int executeUpdate() throws SQLException

CallableStatement

ResultSet

boolean next() throws SQLException
boolean last() throws SQLException
String getString​(int columnIndex) throws SQLException
String getString​(String columnLabel) throws SQLException

java.sql.Date

java.sql.Date extends java.util.Date
Java中有两个Date类,一个是java.util.Date通常情况下用它获取当前时间或构造时间,另一个是java.sql.Date是针对SQL语句使用的,它只包含日期而没有时间部分。两个类型的时间可以相互转化。

java.sql包下给出三个与数据库相关的日期时间类型:

  • Date:表示日期,只有年月日,没有时分秒。会丢失时间;
  • Time:表示时间,只有时分秒,没有年月日。会丢失日期;
  • Timestamp:表示时间戳,有年月日时分秒,以及毫秒。

util.Date与sql.Date的相互转换

批处理、存储过程、事务

参见:Java-JDBC调用批处理、存储过程、事务

示例

package com.runoob.test;
 
import java.sql.*;
 
public class MySQLDemo {
 
    // JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";
 
    // 数据库的用户名与密码,需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "123456";
 
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            // 注册 JDBC 驱动
            Class.forName("com.mysql.jdbc.Driver");
        
            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
        
            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, name, url FROM websites";
            ResultSet rs = stmt.executeQuery(sql);
        
            // 展开结果集数据库
            while(rs.next()){
                // 通过字段检索
                int id  = rs.getInt("id");
                String name = rs.getString("name");
                String url = rs.getString("url");
    
                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 站点名称: " + name);
                System.out.print(", 站点 URL: " + url);
                System.out.print("\n");
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        }catch(SQLException se){
            // 处理 JDBC 错误
            se.printStackTrace();
        }catch(Exception e){
            // 处理 Class.forName 错误
            e.printStackTrace();
        }finally{
            // 关闭资源
            try{
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

猜你喜欢

转载自blog.csdn.net/u013474568/article/details/86084938
今日推荐