JAVA—Jdbc学习

news/2024/5/19 1:46:26 标签: jdbc, mysql, 数据库, java

使用Jdbc连接数据库

java">//1:加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        //2:用户信息和url
        String url="jdbc:mysql://localhost:3306/jpa?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=true";
        //对于mysql8版本,serverTimezone是必须要设置的,否则会报异常
        String username="root"; //数据库连接名
        String password="123456";  //数据库密码

//        3:连接成功,数据库对象,connection代表数据库
        Connection connection = DriverManager.getConnection(url,username,password);

//        4:执行sql对象statement
        Statement statement=connection.createStatement();

//        5:执行sql语句,并返回结果
        String sql="select * from tbl_user";
        ResultSet resultSet=statement.executeQuery(sql);

        while(resultSet.next()){
            System.out.println("id"+resultSet.getObject("id"));
            System.out.println("id"+resultSet.getObject("email"));
            System.out.println("id"+resultSet.getObject("name"));
        }

//        6:关闭所有连接,避免浪费资源
        resultSet.close();
        statement.close();
        connection.close();

不过以上代码耦合性太高,可以写一个配置类,在配置类中放置静态代码,解耦!
首先在src目录下创建一个db.properties配置文件用来放置数据库连接信息

java">driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jpa?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=true
username=root
password=123456
//注意:这里是的对象都不需要引号,否则会报SQL异常(找不到连接名)

开始写工具类
一)首先定义好我们需要用来的变量(包括连接对象,账号密码,返回结果集等):

java">	private static  ResultSet resultset;    //定义数据库返回对象
    private static Connection connection;   //定义数据库连接对象
    private static Statement statement;
    private static String driver;           //定义连接名
    private static String url;              //定义连接地址
    private static String username;         //定义用户名
    private static String password;         //定义密码

二)利用文件流操作读取配置文件中的信息,并且加载连接数据库驱动

java">static{
        try{
            //读取配置文件
            InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);  //加载配置文件
            driver = properties.getProperty("driver"); //从配置文件中读取值
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            Class.forName(driver);//加载类路径

        } catch (Exception e) {
            e.printStackTrace();
        }

三)最后再写两个方法用来返回连接对象和释放资源

java">/**
     * 返回一个connection对象
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
         return DriverManager.getConnection(url, username, password);
    }

    /**
     * 释放资源
     */
    public void ReleaseResource(){
        try{
            if(resultset != null){
                resultset.close();
            }
            if(statement != null){
                statement.close();
            }
            if(connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

最后整合一下就是:

java">
public class JdbcUtils {

    private static  ResultSet resultset;    //定义数据库返回对象
    private static Connection connection;   //定义数据库连接对象
    private static Statement statement;
    private static String driver;           //定义连接名
    private static String url;              //定义连接地址
    private static String username;         //定义用户名
    private static String password;         //定义密码
    static{
        try{
            //读取配置文件
            InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);  //加载配置文件
            driver = properties.getProperty("driver"); //从配置文件中读取值
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            Class.forName(driver);//加载类路径

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回一个connection对象
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
         return DriverManager.getConnection(url, username, password);
    }

    /**
     * 释放资源
     */
    public void ReleaseResource(){
        try{
            if(resultset != null){
                resultset.close();
            }
            if(statement != null){
                statement.close();
            }
            if(connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

写好了工具类再使用jdbc连接数据库的话,就方便很多

java">public class TestSelect {
    public static Connection connection;
    public static Statement statement;

    public static void main(String[] args) throws SQLException {
        TestSelect.Test1();
    }
    public static void Test1() throws SQLException {
        String sql="select * from tbl_user";
        JdbcUtils jdbcUtils = new JdbcUtils();
        connection = jdbcUtils.getConnection();
        statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        while(resultSet.next()){
            System.out.println(resultSet.getString("name"));
        }
        jdbcUtils.ReleaseResource();


    }
}

增删改查的代码基本都是一样的,需要改动的地方也就是

java">ResultSet resultSet = statement.executeQuery(sql);

查询的话就使用executeQuery方法;
删改查就使用executeUpdate方法


http://www.niftyadmin.cn/n/898691.html

相关文章

插入排序的实现

类似冒泡的实现 /*** this is a insert sort** param arr*/public static void insert_sort(int[] arr) {for (int i 1; i < arr.length; i) {for (int j i; j > 0; j--) {if (arr[j] < arr[j - 1]) {int temp arr[j];arr[j] arr[j - 1];arr[j - 1] temp;}}}}改进…

插入排序and希尔排序(逐行讲解!)

import java.util.Arrays;/*** this is the shell sort* 首先先实现插入排序* 再在插入排序的基础上实现希尔排序*/ public class shellsort {/*** this is inser sort* param arr*/public static void insert_sort(int[] arr){/*** 插入排序是每一次拿出一个数&#xff0c;像插…

归并排序(逐行注释!) 递归的使用

/*** 归并排序的实现*/ public class mergesort {/*** 对两个有序数组的归并排序** param arr1 the array* param arr2 the array*/public static int[] merge(int[] arr1, int[] arr2) {int N1 arr1.length;int N2 arr2.length;int i 0;int j 0;int count 0;int ans[] n…

用数组的方式实现ArrayList

/*** this is my ArrayList* param <Object>*/ public class myarraylist<Object> implements Iterable<Object> {private static final int DEFAULT_CAPACITY 10; //用来定义默认数组的长度private int thesize; //用来控制theitems数组的长度(实际也…

用链表实现LinkedList

public class myLinkedList implements Iterable {private int thesize; //存储当前链表的长度private int modcount 0;private Node beginMarker; //链表的头节点&#xff0c;其next指向链表的第一个节点private Node endMarker; //链表的尾节点&#xff0c;其prev指…

快速排序(逐行讲解)

首先需要声明&#xff0c;我这这里并没有图例&#xff0c; 所以将以各位小伙伴先去了解此算法的思想再回过来看代码 /*** 实现快速排序*/ public class quicksort {/*** 快速排序的核心思想其实也是交换* 设立两个指针左指针和右指针&#xff0c;分别指向头和尾&#xff0c;再从…

桶排序基数排序的实现(细致到极致)

希望大家在看代码之前先去看看图解&#xff0c;我在这里就只实现了代码 也可以在底下留言&#xff0c;我会慢慢讲解的 /*** 桶排序和基数排序的实现*/ public class bucketsort {/*** 实现一个最简易桶排序* 主要思想是创建一个超级大的桶&#xff0c;再将每个数按大小放入桶中…

大顶堆的构造堆排序的实现

/*** 堆排序的实现*/ public class heapsort {/*** 将数组arr从下标第i个开始构造成一个大顶堆* param arr 目标数组* param i 从第i个开始构造&#xff08;i的意思也就是需要保证从i开始后面的数已经是大顶堆了&#xff09;* param n 数组的大小*/public static void constr…