IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 大数据 -> JDBC基础 -> 正文阅读

[大数据]JDBC基础

步骤

  1. 导入驱动jar包mysql-connector-java-8.0.23.jar
  2. 注册驱动
  3. 获取数据库连接对象 Connection
  4. 定义sql
  5. 获取执行sql语句的对象Staement
  6. 执行sql语句,接受返回结果
  7. 处理结果
  8. 释放资源
package jdbc.lesson1;

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

public class JdbcDemo01 {
    public static void main(String[] args) throws Exception {
//        导入驱动jar包
//        注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
//        获取数据库连接对象
        Connection root = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop", "root", "123456");
//        定义sql语句
        String sql = "update a set name='djhahd' where id=1";
//       获取执行对象
        Statement statement = root.createStatement();
//        执行
        int i = statement.executeUpdate(sql);
//        处理
        System.out.println(i);
//        释放
        statement.close();
        root.close();
    }
}

各个对象解释

1.DriverManager:驱动管理对象

  1. 注册驱动:告诉程序改执行哪一个数据库的驱动jar,真正注册驱动的是这个对象
  2. 获取数据库连接:

? 参数:url:指定连接的路径

? 语法:jdbc:mysql://ip地址(域名):端口号/数据库名称

? 细节:如果连接本机可以省写为:jdbc:mysql:///数据库名称

注意:mysql5之后的驱动jar包可以省略注册驱动的步骤

2.Connection:数据库连接对象

  1. 获取执行sql的对象
  2. 管理事务:
    1. 开启事务 setAutoCommit
    2. 提交事务 commit
    3. 回滚事务 rollback

3.Statement:执行sql的对象

  1. 执行sql语句
    1. executeUpdate:执行DML语句或DDL语句,返回值是影响的行数,是一个int类型
    2. executeQuery:执行DQL语句,返回结果集

4.ResultSet:结果集对象,封装查询结果

  1. next:游标向下移动一行,判断当前行是否是最后有行

  2. getxxx():获取数据

    1. xx代表数据类型
    2. 获取int类型时,需要列的编号,从1开始
    3. 获取string时,需要列的名称

    注意: 使用循环判断游标是否是最后一行

5.PreparedStatement:执行sql的对象(防注入问题)

  1. 先预编译:参数使用?占为符
  2. 定义sql语句,值用?代替
  3. 获取sql的执行对象
  4. 给?赋值
    1. 方法:setxxx()
    2. 参数1.为?的位置,1开始
    3. 参数2为值
  5. 执行sql语句,不需要传递sql语句

释放资源时尽量判断是否为空,防止空指针异常

将数据库中数据表的数据封装为对象,然后装载集合,返回

1.定义一个类

package cn.itcast.damain;

import java.util.Date;

/**
 * 封装数据表数据的类
 */
public class Emp {
//    根据数据库列的类型,逐个声明
    private int id;
    private String name,pwd,sex;
    private Date birthday;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

2.定义方法

package jdbc;

import cn.itcast.damain.Emp;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定义一个方法,查询数据表
 */
public class jdbcdemo2 {
    public static void main(String[] args) {
       List<Emp> list = new jdbcdemo2().findAll();
        System.out.println(list);
    }
    /**
     * 查询数据表的所有对象
     * @return
     */
    public List<Emp> findAll(){
        Connection conn = null;
        Statement st = null ;
        ResultSet re = null;
        List<Emp> list = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

             conn = DriverManager.getConnection("jdbc:mysql:///shop","root","123456");

            String sql = "select * from a";
            st = conn.createStatement();

             re = st.executeQuery(sql);
//            遍历集合,封装对象,装载集合
            Emp emp =null;
            list = new ArrayList<Emp>();
            while (re.next()){
                int id = re.getInt("id");
                String name = re.getString("name");
                String pwd  = re.getString("pwd");
                String sex  = re.getString("sex");
                Date birthday  = re.getDate("birthday");

                emp = new Emp();
                emp.setId(id);
                emp.setName(name);
                emp.setBirthday(birthday);
                emp.setPwd(pwd);
                emp.setSex(sex);

//                装进集合
                list.add(emp);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            if (re!=null){
                try {
                    re.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                if (st!=null){
                    try {
                        st.close();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                    if (conn!=null){
                        try {
                            conn.close();
                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                    }
                }
            }
        }
        return list;
    }
}

3.实现方法

//因为方法是list返回的,所有要list
List<Emp> list = new jdbcdemo2().findAll();
System.out.println(list);

JDBC工具类

获取配置文件的路径

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?characterEncoding=utf8&useSSL=true&serverTimezone=UTC&rewriteBatchedStatements=true
username=root
password=123456
package com.tzeao.test.lesson01.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 获取写的资源文件
 * @author 童泽沼
 */
public class JdvcUtils {
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {
        try {

//             InputStream   is   =   getClass().getClassLoader().getResourceAsStream("helloworld.properties");
//             getClass():取得当前对象所属的Class对象
//             getClassLoader():取得该Class对象的类装载器
//             类装载器负责从Java字符文件将字符流读入内存,并构造Class类对象,在你说的问题哪里,通过它可以得到一个文件的输入流
//             获取文件getResourceAsStream()

            InputStream in = JdvcUtils.class.getClassLoader().getResourceAsStream("db.properties");
//          表示一个持久的属性集.属性列表中每个键及其对应值都是一个字符串。
            Properties properties = new Properties();
//             从输入流中读取属性列表(键和元素对)。
            properties.load(in);

//            通过键获取值
            String driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

//            加载驱动,只加载一次
            Class.forName(driver);

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

    /**
     * @return 返回数据库
     * @throws SQLException 获取连接
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    /**
     * 释放连接资源
     *
     * @param conn
     * @param st
     * @param rs
     * @throws SQLException
     */
    public static void release(Connection conn, Statement st, ResultSet rs) throws SQLException {
        if (rs != null) {
            rs.close();
        }
        if (st != null) {
            st.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}

 ClassLoader classLoader = JdvcUtils.class.getClassLoader();
  URL res = classLoader.getResource(”配置文件名字“);
        String path = res.getPath();

登录界面

package jdbc.lesson1;

import com.tzeao.test.lesson01.utils.JdvcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class jdbcDemo02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String name = scanner.next();
        String password = scanner.next();

        Boolean jdbcDemo02 = new jdbcDemo02().login(name, password);
        if (jdbcDemo02){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }

    }
    public Boolean login(String usernmae,String pwssword){

        if (usernmae == null || pwssword == null){
            return false;
        }
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {

            conn = JdvcUtils.getConnection();

            String sql = "select * from users where `NAME`='"+usernmae+"'and`PASSWORD`='"+pwssword+"'";

            st = conn.createStatement();

            rs = st.executeQuery(sql);

            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                JdvcUtils.release(conn,st ,rs);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return false;
    }
}

事务

手动制造异常

int a =1/0

关闭自动提交就是开启事务

catch里面进行事务回滚

所有sql语句执行完毕时提交事务

数据库连接池

好处:节约资源,用户访问高效

实现:标准接口:DataSource

c3p0

c3p0-0.9.5.5.jar

mchange-commons-java-0.2.19.jar

配置

名字要命名为c3p0-config.xml

<c3p0-config>  <default-config>    <property name="driverClass">com.mysql.jdbc.Driver</property>    <property name="jdbcUrl">jdbc:mysql://localhost/std</property>    <property name="user">root</property>    <property name="password">root</property>        <property name="initialPoolSize">10</property>    <property name="maxIdleTime">30</property>    <property name="maxPoolSize">100</property>    <property name="minPoolSize">10</property>    <property name="maxStatements">200</property>  </default-config>  <!-- This app is massive! -->  <named-config name="intergalactoApp">     <property name="acquireIncrement">50</property>    <property name="initialPoolSize">100</property>    <property name="minPoolSize">50</property>    <property name="maxPoolSize">1000</property>    <!-- intergalactoApp adopts a different approach to configuring statement caching -->    <property name="maxStatements">0</property>     <property name="maxStatementsPerConnection">5</property>    <!-- he's important, but there's only one of him -->    <user-overrides user="master-of-the-universe">       <property name="acquireIncrement">1</property>      <property name="initialPoolSize">1</property>      <property name="minPoolSize">1</property>      <property name="maxPoolSize">5</property>      <property name="maxStatementsPerConnection">50</property>    </user-overrides>  </named-config></c3p0-config>

JAVA编写

conn.close();//归还
package C3P0;import com.mchange.v2.c3p0.ComboPooledDataSource;import javax.sql.DataSource;import java.sql.Connection;import java.sql.SQLException;/** * c3p0演示 */public class C3P0 {    public static void main(String[] args) {//        创建数据库连接池        DataSource ds = new ComboPooledDataSource();//        获取连接对象        Connection conn = null;        try {            conn = ds.getConnection();        } catch (SQLException throwables) {            throwables.printStackTrace();        }        System.out.println(conn);    }}

Druid

  1. 导入jar包 druid-1.2.3.jar

  2. 配置文件

    druid.properties

    driverClassName=com.mysql.cj.jdbc.Driverurl=jdbc:mysql://localhost:3306/jdbcstudy?characterEncoding=utf8&useSSL=true&serverTimezone=UTC&rewriteBatchedStatements=trueusername=rootpassword=123456initialSize=5maxActive=10maxWait=3000maxIdle=8minIdle=3
    

?

  1. 使用
package druid;import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;import java.io.InputStream;import java.sql.Connection;import java.util.Properties;public class druiddemo1 {    public static void main(String[] args) throws Exception {//        加载配置文件        Properties pr = new Properties();        InputStream in = druiddemo1.class.getClassLoader().getResourceAsStream("druid.properties");        pr.load(in);//        获取连接池对象,通过工厂模式        DataSource ds = DruidDataSourceFactory.createDataSource(pr);//        获取连接        Connection conn = ds.getConnection();        System.out.println(conn);    }}

定义Druid工具类

package utilss;import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;import java.io.InputStream;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;/** * Druid工具类 */public class JDBCUtil {    //    定义成员变量    private static DataSource ds;    static {        try {//        加载配置文件            Properties pro = new Properties();            InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties");            pro.load(in);            //       获取DataSource            ds = DruidDataSourceFactory.createDataSource(pro);        } catch (Exception e) {            e.printStackTrace();        }    }    //    获取连接方法    public static Connection getConnection() throws SQLException {        return ds.getConnection();    }    //    释放资源    public static void close(Statement st, Connection conn) {        if (st != null) {            try {                st.close();            } catch (SQLException throwables) {                throwables.printStackTrace();            }        }        if (conn != null) {            try {                conn.close();//归还资源            } catch (SQLException throwables) {                throwables.printStackTrace();            }        }    }    public static void close(ResultSet rs, Statement st, Connection conn) {        if (rs != null) {            try {                rs.close();            } catch (SQLException throwables) {                throwables.printStackTrace();            }        }        if (st != null) {            try {                st.close();            } catch (SQLException throwables) {                throwables.printStackTrace();            }        }        if (conn != null) {            try {                conn.close();//归还资源            } catch (SQLException throwables) {                throwables.printStackTrace();            }        }    }    //    获取连接池    public static DataSource getDataSoure() {        return ds;    }}

使用

import utilss.JDBCUtil;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;public class Druidgjuleoi {    public static void main(String[] args) {        Connection conn = null;        PreparedStatement st =null;        try {            conn = JDBCUtil.getConnection();            String sql = "insert into users values(?,?,?,?,?)";             st = conn.prepareStatement(sql);            st.setInt(1, 9);            st.setString(2, "9");            st.setString(3, "9");            st.setString(4, "9");            st.setDate(5, new java.sql.Date(System.currentTimeMillis()));            int i = st.executeUpdate();        } catch (SQLException throwables) {            throwables.printStackTrace();        }finally {            JDBCUtil.close(st, conn);        }    }}

Spring JDBC

对JDBC的封装

JdbcTemplate使用步骤

  1. 准备DruidDataSource连接池

  2. 导入依赖的jar包

  3. 创建JdbcTemplate对象,传入Druid连接池

  4. 调用executeupdatequeryXxx等方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dEGurjMr-1632574760653)(image-20210410002031321.png)]

package jdbctemplate;import org.springframework.jdbc.core.JdbcTemplate;import utilss.JDBCUtil;public class jdbcTemplateDemo {    public static void main(String[] args) {//        创建Template对象        JdbcTemplate template = new JdbcTemplate(JDBCUtil.getDataSoure());        String sql = "update users set `NAME`='52663' where id=?";//        args表示问好的值        int update = template.update(sql, 9);        System.out.println(update);    }}

执行DML语句

package jdbctemplate;import org.junit.Test;import org.springframework.jdbc.core.JdbcTemplate;import utilss.JDBCUtil;public class jdbcTemplateDemo1 {//    Junit单元测试,可以让方法独立执行,不需要依赖主函数//    如果控制台变红则表示测试失败,绿色表示不一定表示成功,具体看输出情况private JdbcTemplate template = new JdbcTemplate(JDBCUtil.getDataSoure());    @Test    public void test1(){        String sql = "update users set `NAME`='52663' where id=1";//        args表示问好的值        int update = template.update(sql);        System.out.println(update);    }    @Test    public void test2(){        String sql = "insert into users values(id=1,`NAME`='52663',null,null,null)";//        args表示问好的值        int update = template.update(sql);        System.out.println(update);    }    @Test    public void test3(){        String sql = "delete from users where id=9";//        args表示问好的值        int update = template.update(sql);        System.out.println(update);    }}

执行DQL语句

   @Test
    public void test4() {
        String sql = "select * from users where id=8";
//        queryForMap返回Map集合
//        这个方法查询的结果长度为一,如果多条会保错
        Map<String, Object> update = template.queryForMap(sql);
        System.out.println(update);
    }
    @Test
    public void test5() {
        String sql = "select * from users";
//        queryForList返回List集合
//        将查导的每一条数据装载在Map集合里面,再将Map集合装载在List集合离
        List<Map<String, Object>> maps = template.queryForList(sql);
        System.out.println(maps);
    }
    @Test
    public void test6() {
        String sql = "select * from users";
//        将数据封装到对象后再装载进List集合
//        对象自己编写
        template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
//  需要遍历输出
    }
    @Test
    public void test7() {
        String sql = "select count(id) from users";
//打印查询总记录数,封装为对象
        Long aLong = template.queryForObject(sql, Long.class);
        System.out.println(aLong);
    }

拓展

package jdbctemplate;

import org.junit.Test;

public class jdbcTemplateDemo1 {
//    Junit单元测试,可以让方法独立执行,不需要依赖主函数
//     如果控制台变红则表示测试失败,绿色表示不一定表示成功,具体看输出情况
    
    @Test
    public void test1(){
        System.out.println("asjkdn");
    }
}
  大数据 最新文章
实现Kafka至少消费一次
亚马逊云科技:还在苦于ETL?Zero ETL的时代
初探MapReduce
【SpringBoot框架篇】32.基于注解+redis实现
Elasticsearch:如何减少 Elasticsearch 集
Go redis操作
Redis面试题
专题五 Redis高并发场景
基于GBase8s和Calcite的多数据源查询
Redis——底层数据结构原理
上一篇文章      下一篇文章      查看所有文章
加:2021-09-26 10:14:50  更:2021-09-26 10:17:37 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/20 8:18:36-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码