JDBC: 2.初级教程

搭建

依赖

 <dependencies>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
    </dependencies>

jdbc.properties

url=jdbc:mysql://localhost:3306/phone_book_console?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username=root
pwd=root
driver=com.mysql.jdbc.Driver

封装JDBC工具类

package com.utils;

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

/**
 * JDBC工具类
 */
public class JdbcUtils {

    //成员变量,作用全局
    private static String url;
    private static String username;
    private static String pwd;

    //静态块,只初始化一次,用来初始化jdbc.properties和注册数据库驱动
    static {
        try {
            //实例化Properties对象
            Properties properties = new Properties();
            //获取读取properties文件的字节输入流对象
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //读取properties文件并解析
            properties.load(is);
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            pwd = properties.getProperty("pwd");
            String driver = properties.getProperty("driver");
            //加载并注册数据库驱动,一次即可
            Class.forName(driver);

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

    //获取数据库连接对象
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, pwd);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //关闭连接对象
    public static void closeConnection(Connection connection) {
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //提交事务
    public static void commit(Connection connection) {
        try {
            connection.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //事务回滚
    public static void rollback(Connection connection) {
        try {
            connection.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //关闭Statement对象
    public static void closeStatement(Statement statement) {
        try {
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //关闭ResultSet
    public static void closeResultSet(ResultSet resultSet) {
        try {
            resultSet.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //DML操作时关闭资源
    public static void closeResource(Statement statement, Connection connection) {
        //先关闭Statement对象
        closeStatement(statement);
        //在关闭Connection对象
        closeConnection(connection);
    }

    //查询时关闭资源
    public static void closeResource(ResultSet resultSet, Statement statement, Connection connection) {
        //先关闭ResultSet
        closeResultSet(resultSet);
        //在闭Statement对象
        closeStatement(statement);
        //最后关闭Connection对象
        closeConnection(connection);
    }
}

Driver接口

Driver接口的作用是来定义数据库驱动对象应该具备的一些能力,比如与数据库建立连 接的方法的定义,该接口是提供给数据库厂商使用的,所有支持 java 语言连接的数据库都实现了该接口,实现该接口的类我们称之为数据库驱动类

DriverManager类

简介

DriverManager是驱动程序管理器,是负责管理数据库驱动程序的,驱动注册以后,会保存在DriverManager中的已注册列表中 DriverManager 通过实例化的数据库驱动对象,能够建立应用程序与数据库之间建立连接并返回Connection接口类型的数据库连接对象

getConnection()

getConnection(String jdbcUrl, String user, String password) 该方法通过访问数据库的 url、用户以及密码,返回对应的数据库的 Connection 对象

示例:连接mysql数据库

String url = "jdbc:mysql://localhost:3306/test?useSSL=false";

String name = "root";

String pwd = "root";

//通过反射实现数据库驱动的加载与注册

Class.forName("com.mysql.jdbc.Driver");

Connection connection = DriverManager.getConnection(url, name, pwd); System.out.println(connection);

Connection接口

简介

Connection是数据库的连接(会话)对象,对数据库的一切操作都是在这个连接基础之上进行的,我们可以通过该对象执行sql语句并返回结果

方法

createStatement():创建向数据库发送 sql 的 Statement 接口类型的对象
preparedStatement(sql):创建向数据库发送预编译 sql 的 PrepareSatement 接口类型的对象
setAutoCommit(boolean autoCommit):设置事务是否自动提交
commit():在链接上提交事务
rollback():在此链接上回滚事务

Statement

简介

用于执行静态 SQL 语句并返回它所生成结果的对象,由 createStatement 创建,用于发送简单的 SQL 语句(不支持动态绑定)

注意

由于Statement对象是一个执行静态SQL语句的对象,所以该对象存在SQL注入风险

方法

execute(String sql):执行参数中的 SQL,返回是否有结果集。

executeQuery(String sql):运行 select 语句,返回 ResultSet 结果集。 executeUpdate(String sql):运行 insert/update/delete 操作,返回更新的行数。 addBatch(String sql):把多条 sql 语句放到一个批处理中。

executeBatch():向数据库发送一批 sql 语句执行。

添加数据


/**
 * Statement对象的使用
 */
public class StatementTest {


    /**
     * 添加用户
     */
    public void insertUsers(String username,int userage){
        Connection connection = null;
        Statement statement = null;
        try{
            //获取Connection对象。
            connection = JdbcUtils.getConnection();
            //获取Statement对象
            statement = connection.createStatement();
            //定义需要执行的SQL语句
            String sql = "insert into users values(default,'"+username+"',"+userage+")";
            //执行SQL,返回boolean值,如果sql有结果集返回,那么返回值为true,如果没有结果集返回,则返回false。
            boolean execute = statement.execute(sql);
            System.out.println(execute);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtils.closeResource(statement,connection);
        }
    }
}         

修改数据

 /**
     * 修改用户信息
     */
    public void updateUsers(int userid,String username,int userage){
        Connection connection = null;
        Statement statement = null;
        try{
            //获取连接对象
            connection = JdbcUtils.getConnection();
            //获取Statement对象
            statement = connection.createStatement();
            //定义sql语句
            String sql ="update users set username='"+username+"',userage="+userage+" where userid="+userid;
            //执行sql语句
            int i = statement.executeUpdate(sql);
            System.out.println(i);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtils.closeResource(statement,connection);
        }
    }

删除数据


    /**
     * 根据用户ID删除用户
     */
    public void deleteUsersById(int userid){
        Connection connection =null;
        Statement statement = null;
        try{
            //获取数据库连接
            connection = JdbcUtils.getConnection();
            //获取Statement对象
            statement = connection.createStatement();
            //定义执行删除语句
            String sql = "delete from users where userid="+userid;
            //执行sql
            int i = statement.executeUpdate(sql);
            System.out.println(i);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtils.closeResource(statement,connection);
        }
    }

preparedStatement

简介

继承自Statement接口,由preparedStatement方法创建, PreparedStatement具有预编译SQL语句能力,所以PreparedStatement对象比 Statement 对象的效率更高, 由于实现了动态的参数绑定,所以可以防止SQL注入,所以我们一般都使用PreparedStatement

特点

1.PreparedStatement 接口继承 Statement 接口
2.PreparedStatement 效率高于 Statement
3.PreparedStatement 支持动态绑定参数
4.PreparedStatement 具备 SQL 语句预编译能力
5.使用 PreparedStatement 可防止出现 SQL 注入问题

方法

addBatch():把当前 sql 语句加入到一个批处理中
execute():执行当前 SQL,返回个 boolean 值
executeUpdate():运行 insert/update/delete 操作,返回更新的行数。
executeQuery():执行当前的查询,返回一个结果集对象
setDate(int parameterIndex, Date x):向当前SQL语句中的指定位置绑定一个java.sql.Date值
setDouble(int parameterIndex, double x): 向当前 SQL 语句中的指定位置绑定一个 double值
setFloat(int parameterIndex, float x): 向当前 SQL 语句中的指定位置绑定一个 float 值
setInt(int parameterIndex, int x): 向当前 SQL 语句中的指定位置绑定一个 int 值
setString(int parameterIndex, String x):向当前 SQL 语句中的指定位置绑定一个 String 值

添加数据

 /**
     * PreparedStatement使用的测试类
     */
    public class PreparedStatementTest {
        /**
         * 添加用户
         */
        public void insertUsers(String username,int userage){
            Connection connection = null;
            PreparedStatement ps = null;
            try{
                //获取数据库连接
                connection = JdbcUtils.getConnection();
                //定义Sql。?是PreparedStatement对象中的绑定参数的占位符。问号的位置是从1开始计数的
                String sql = "insert into users values(default,?,?)";
                //创建PreparedStatement对象
                ps = connection.prepareStatement(sql);
                //完成参数的绑定
                ps.setString(1,username);
                ps.setInt(2,userage);
                int i = ps.executeUpdate();
                System.out.println(i);
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                JdbcUtils.closeResource(ps,connection);
            }
        }
    }

更新数据

/**
     * 根据用户ID修改用户姓名与年龄
     */
    public void updateUsersById(int userid,String username,int userage){
        Connection connection = null;
        PreparedStatement ps = null;
        try{
            //获取数据库连接对象
            connection = JdbcUtils.getConnection();
            //创建PreparedStatement对象
            ps = connection.prepareStatement("update users set username = ?,userage=? where userid = ?");
            //参数绑定
            ps.setString(1,username);
            ps.setInt(2,userage);
            ps.setInt(3,userid);
            int i = ps.executeUpdate();
            System.out.println(i);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtils.closeResource(ps,connection);
        }
    }

删除数据

  /**
     * 根据用户ID删除指定用户
     */
    public void deleteUsersById(int userid){
        Connection conn = null;
        PreparedStatement ps = null;
        try{
            //获取数据库连接对象
            conn = JdbcUtils.getConnection();
            //创建PreparedStatement对象
            ps = conn.prepareStatement("delete from users where userid = ? ");
            //绑定参数
            ps.setInt(1,userid);
            int i = ps.executeUpdate();
            System.out.println(i);
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtils.closeResource(ps,conn);
        }
    }

ResultSet

简介

ResultSet用来存放数据库查询操作获得结果集,通过对ResultSet的操作可以获取查询到的结果集数据

注意

ResultSet 对象中存放的并不是我们查询到的所有的结果集,它采用分块加载的方式来载入结果集数据

特点

ResultSet对象具有指向其当前数据行的指针,最初指针被置于第一行之前,next方法将指针移动到下一行, 因为该方法在ResultSet对象中没有下一行时返回false,所以可以在 while 循环中使用它来迭代结果集, 默认的ResultSet对象仅有一个向前移动的指针,因此,只能迭代它一次,并且只能按从第一行到最后一行的顺序进行, ResultSet接口提供用于获取当前行检索列值的获取方法(getBoolean、getLong 等),可以使用列的索引位置或列的名称检索值,

方法

getString(int index)、getString(String columnName):获得在数据库里是 varchar、char 等类型的数据对象。
getFloat(int index)、getFloat(String columnName):Float(int index)、getFloat(String columnName)
getDate(int index)、getDate(String columnName):获得在数据库里是 Date 类型的数据。
getBoolean(int index)、getBoolean(String columnName):获得在数据库里是 Boolean 类型的数据。
getObject(int index)、getObject(String columnName):获取在数据库里任意类型的数据。 

查询所有

 /**
         * 查询所有用户
         */
        public void selectUsersAll(){
            Connection connection = null;
            PreparedStatement ps = null;
            ResultSet resultSet = null;
            try{
                //获取数据库连接
                connection = JdbcUtils.getConnection();
                //创建PreparedStatement对象
                ps = connection.prepareStatement("select * from users");
                //执行查询
                resultSet = ps.executeQuery();
                //操作ResultSet对象获取查询的结果集
                while(resultSet.next()){
                    //获取列中的数据
                    int userid = resultSet.getInt("userid");
                    String username = resultSet.getString("username");
                    int userage = resultSet.getInt("USERAGE");
                    System.out.println(userid+" "+username+" "+userage);


                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                JdbcUtils.closeResource(resultSet,ps,connection);
            }
        }

模糊查询

 /**
     * 根据用户名称模糊查找用户信息
     */
    public List<Users> fuzzyQuery(String username){
        List<Users> list= new ArrayList<>();


        Connection conn =null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            //获取数据库连接
            conn = JdbcUtils.getConnection();
            //创建PreparedStatement对象
            ps = conn.prepareStatement("select * from users where username like ?");
            //参数绑定
            ps.setString(1,username);
            //执行sql语句
            rs = ps.executeQuery();
            while(rs.next()){
                Users user = new Users();
                user.setUserid(rs.getInt("userid"));
                user.setUsername(rs.getString("username"));
                user.setUserage(rs.getInt("userage"));
                list.add(user);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtils.closeResource(rs,ps,conn);
        }
        return list;
    }


    public static void main(String[] args) {
        FuzzyQueryTest ft = new FuzzyQueryTest();
        List<Users> users = ft.fuzzyQuery("%d%");
        for(Users user1:users){
            System.out.println(user1.getUserid()+" "+user1.getUsername()+" "+user1.getUserage());
        }
    }

动态条件查询


    /**
     * 动态条件查询Users
     */
    public List<Users> queryUsers(Users users){
        List<Users> list= new ArrayList<>();


        Connection conn =null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            //获取数据库连接
            conn = JdbcUtils.getConnection();
            //拼接查询SQL语句
            String sql = this.generateSql(users);
            System.out.println(sql);
            //创建PreparedStatement对象
            ps = conn.prepareStatement(sql);


            //执行sql语句
            rs = ps.executeQuery();
            while(rs.next()){
                Users user = new Users();
                user.setUserid(rs.getInt("userid"));
                user.setUsername(rs.getString("username"));
                user.setUserage(rs.getInt("userage"));
                list.add(user);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JdbcUtils.closeResource(rs,ps,conn);
        }
        return list;
    }


    /**
     * 生成动态条件查询sql
     */
    private String generateSql(Users users){
        StringBuffer sb = new StringBuffer("select * from users where 1=1 ");


        if(users.getUserid() > 0){
            sb.append(" and userid = ").append(users.getUserid());
        }
        if(users.getUsername() !=null &&users.getUsername().length() > 0){
            sb.append(" and username = '").append(users.getUsername()).append("'");
        }
        if(users.getUserage() > 0){
            sb.append(" and userage = ").append(users.getUserage());
        }
        return sb.toString();
    }


    public static void main(String[] args) {
        DynamicConditionQueryTest dt = new DynamicConditionQueryTest();
        Users users = new Users();
        users.setUsername("Oldlu");
        users.setUserage(20);
        List<Users> list = dt.queryUsers(users);
        for(Users user1:list){
            System.out.println(user1.getUserid()+" "+user1.getUsername()+" "+user1.getUserage());
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

月木@

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

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

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

打赏作者

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

抵扣说明:

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

余额充值