jdbc学习

入门

package com.ithaojie.jdbc;

import com.sun.xml.internal.ws.org.objectweb.asm.ClassAdapter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class jdbcDemo {

    public static void main(String[] args)throws Exception{
//       1. 加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
//        2.获得链接
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_test1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC","root","123456");
//        3.执行sql
//        3.1获得执行sql语句的对象
        Statement statement=con.createStatement();
//        3.2编写sql语句
        String sql ="select * from user";
//        3.3执行sql语句
        ResultSet resultSet=statement.executeQuery(sql);
//        3.4遍历结果集
        while(resultSet.next()){
            System.out.print(resultSet.getInt("id")+" ");
            System.out.print(resultSet.getString("username")+" ");
            System.out.print(resultSet.getString("password")+" ");
            System.out.print(resultSet.getString("nickname")+" ");
            System.out.print(resultSet.getString("age")+" ");
            System.out.println();
        }
//        4.释放资源
        resultSet.close();
        statement.close();
        con.close();

    }

}

JDBC API

Driver

  • 建立sql连接
Connection conn = DriverManager.getConnection( 
      "jdbc:somejdbcvendor:other data needed by some jdbc vendor", // URL
      "myLogin", // 用户名
      "myPassword" ); // 密碼

Connection 与数据库连接对象

  • 创建执行sql语句的对象
    • Statement 执行sql语句
    • PreparedStatement执行sql语句,有预编译,解决sql注入漏洞

Statement 执行sql语句

  • 执行sql

boolean execute(String sql)
执行增删改查
ResultSet executeQuery(String sql)
执行查询
int executeUpdate(String sql)
执行增删改 返回修改的条目数

  • 执行批处理sql语句

addBatch

ResultSet 结果集

查询到的数据

  • 结果集的遍历
    • boolean next():指向下一行
  • 结果集的获取
    • int getInt(int columnIndex)列号
    • int getInt(String columnLabel)列名
    • String getString(int columnIndex) 列号
    • String getString(String columnLabel) 列名
    • Object getObject(String columnLabel)任意类型

释放连接

package com.runoob.test;
 
import java.sql.*;
 
public class MySQLDemo {
 
    // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";
 
    // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
    //static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
    //static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
 
 
    // 数据库的用户名与密码,需要根据自己的设置
    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(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!");
    }
}

增删改查CRUD

表结构

package com.ithaojie.jdbc;

import java.sql.*;

public class jdbcDemo1 {


    public static void main(String[] args) {
        Connection con = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
//        2.获得链接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_test1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC", "root", "123456");
//        3.执行sql
//        3.1获得执行sql语句的对象
            statement = con.createStatement();
//        3.2编写sql语句
            String sql = "insert into user values (null,'d','123','小黄',30)";
//        3.3执行sql语句
            int x = statement.executeUpdate(sql);
            System.out.println(x);
            sql = "select * from user";
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                System.out.print(resultSet.getObject("id") + " ");
                System.out.print(resultSet.getString("username") + " ");
                System.out.print(resultSet.getString("password") + " ");
                System.out.print(resultSet.getString("nickname") + " ");
                System.out.print(resultSet.getString("age") + " ");
                System.out.println();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try{
                if(statement!=null) statement.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(con!=null) con.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
    }
}

package com.ithaojie.jdbc;

import java.sql.*;

public class jdbcDemo1 {


    public static void main(String[] args) {
        Connection con = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
//        2.获得链接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_test1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC", "root", "123456");
//        3.执行sql
//        3.1获得执行sql语句的对象
            statement = con.createStatement();
//        3.2编写sql语句
            String sql = "update user set password='123456',nickname='哈哈' where id=6";
//        3.3执行sql语句
            int x = statement.executeUpdate(sql);
            System.out.println(x);
            sql = "select * from user";
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                System.out.print(resultSet.getObject("id") + " ");
                System.out.print(resultSet.getString("username") + " ");
                System.out.print(resultSet.getString("password") + " ");
                System.out.print(resultSet.getString("nickname") + " ");
                System.out.print(resultSet.getString("age") + " ");
                System.out.println();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try{
                if(statement!=null) statement.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(con!=null) con.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

package com.ithaojie.jdbc;

import java.sql.*;

public class jdbcDemo1 {


    public static void main(String[] args) {
        Connection con = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
//        2.获得链接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_test1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC", "root", "123456");
//        3.执行sql
//        3.1获得执行sql语句的对象
            statement = con.createStatement();
//        3.2编写sql语句
            String sql = "delete from  user where id=6";
//        3.3执行sql语句
            int x = statement.executeUpdate(sql);
            System.out.println(x);
            sql = "select * from user";
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                System.out.print(resultSet.getObject("id") + " ");
                System.out.print(resultSet.getString("username") + " ");
                System.out.print(resultSet.getString("password") + " ");
                System.out.print(resultSet.getString("nickname") + " ");
                System.out.print(resultSet.getString("age") + " ");
                System.out.println();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try{
                if(statement!=null) statement.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(con!=null) con.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

package com.ithaojie.jdbc;

import java.sql.*;

public class jdbcDemo1 {


    public static void main(String[] args) {
        Connection con = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
//        2.获得链接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_test1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC", "root", "123456");
//        3.执行sql
//        3.1获得执行sql语句的对象
            statement = con.createStatement();
//        3.2编写sql语句
            String sql = "select * from user where id=2";
//        3.3执行sql语句

            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                System.out.print(resultSet.getObject("id") + " ");
                System.out.print(resultSet.getString("username") + " ");
                System.out.print(resultSet.getString("password") + " ");
                System.out.print(resultSet.getString("nickname") + " ");
                System.out.print(resultSet.getString("age") + " ");
                System.out.println();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try{
                if(statement!=null) statement.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(con!=null) con.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

jdbc工具类的提取

上面增删改查很多过程都是重复的,只有sql语句不同,抽取之中共同点,抽象成一个工具类

package com.ithaojie.jdbc;

import java.sql.*;

public class jdbcUtils {

    private static final String driverClassname;
    private static final String url;
    private static final String username;
    private static final String password;

    static {
        driverClassname = "com.mysql.cj.jdbc.Driver";
        url = "jdbc:mysql://localhost:3306/jdbc_test1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
        username = "root";
        password = "123456";
    }

    public static void loaderDriver() {
        try {
            Class.forName(driverClassname);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection con = null;
        loaderDriver();
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return con;
    }

    public static void release(Statement statement, Connection connection) {
        try {
            if (statement != null) statement.close();
        } catch (SQLException se2) {
            se2.printStackTrace();
        }// 什么都不做
        try {
            if (connection != null) connection.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }

    public static void release(ResultSet resultSet, Statement statement, Connection connection) {

        try {
            if (resultSet != null)
                resultSet.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        try {
            if (statement != null) statement.close();
        } catch (SQLException se2) {
            se2.printStackTrace();
        }// 什么都不做
        try {
            if (connection != null) connection.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }
}

测试demo

package com.ithaojie.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class jdbcDemo3 {
    /*使用工具类*/
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = jdbcUtils.getConnection();
            statement = connection.createStatement();
            String sql = "select * from user";
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                System.out.print(resultSet.getObject("id") + " ");
                System.out.print(resultSet.getString("username") + " ");
                System.out.print(resultSet.getString("password") + " ");
                System.out.print(resultSet.getString("nickname") + " ");
                System.out.print(resultSet.getString("age") + " ");
                System.out.println();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jdbcUtils.release(resultSet,statement,connection);
        }
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我定亲手擦亮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值