JDBC详解

JDBC是什么?

JDBC是Sun公司提供的一套专门用于Java和数据库进行连接的API,定义了数据库连接的规范.

如何通过JDBC和数据库进行连接并执行SQL语句?

  • 在Maven项目pom文件中引入mysql驱动的依赖
<dependencies>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
    </dependencies>
    <properties>
        <!-- 设置 JDK 版本为 1.8 -->
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
        <!-- 设置编码为 UTF-8 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    </properties>

使用实例

public class Demo1 {
    public static void main(String[] args) throws SQLException {
        //1建立连接
        Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/empdb?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false", "root", "root");
        //2创建执行SQL语句的对象
        System.out.println("连接对象"+conn);
        Statement s = conn.createStatement();
        //3执行SQL语句
        s.execute("create table jdbct1(id int)");
        
//执行插入数据的SQL语句
//        s.executeUpdate("insert into emp(name) values('tom')");
        //执行修改
//        s.executeUpdate("update emp set name = 'jerry' where name = 'tom'");
        //执行删除
//        s.executeUpdate("delete from emp where name = 'jerry'");
        //执行查询
        ResultSet resultSet = s.executeQuery("select name,sal,job from emp");
        //遍历结果集对象
        while (resultSet.next()) {
            String name = resultSet.getString("name");
            double sal = resultSet.getDouble("sal");
            String job = resultSet.getString("job");
            System.out.println(name + sal + job);
        }
        //4关闭资源,断开连接
        conn.close();
        System.out.println("执行完毕");
    }
}

Statement:执行SQL语句的对象

  • execute(“sql”);可以执行任意sql语句,但是推荐执行DDL
  • int row = executeUpdate(“sql”) 执行增删改,返回值为生效的行数
  • ResultSet s = executeQuery(“sql”) 执行查,返回值是查询到的结果

DBCP数据库连接池

作用:重用连接,避免频繁创建销毁连接造成的资源浪费

如何使用连接池?

  • 添加依赖
<!-- 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
  • 代码示例
public class Demo05 {
    @Test
    public void test1() throws SQLException {
        //获取连接池对象
        DruidDataSource ds = new DruidDataSource();
        //设置连接的数据库信息
        ds.setUrl("jdbc:mysql://localhost:3306/empdb?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false");
        ds.setUsername("root");
        ds.setPassword("root");
        //设置初始连接数量
        ds.setInitialSize(3);
        //设置最大的连接数量
        ds.setMaxActive(5);
        //获取连接池中的连接  异常抛出
        Connection conn = ds.getConnection();
        System.out.println(conn);
    }
}

连接对象中的主要方法

createStatement(String sql) 创建SQL语句的执行对象 返回值类型:Statement
prepareStatement(String sql) 创建预编译SQL的对象, 返回值类型:PreparedStatement.此方法可以有效防止SQL注入的问题
代码示例:

PreparedStatement ps = conn.prepareStatement("select count(*) from user where username=? and password=?");
//替换SQL语句中的 ? 其中 1 和 2 代表的是?的位置
//如果替换?时 使用的是setString,字符串的两边会自动添加引号
ps.setString(1,username);
ps.setString(2,password);
ResultSet resultSet = ps.executeQuery();//执行SQL查询
resultSet.next();//指针下移
if (resultSet.getInt(1) == 1){
	System.out.println("登录成功!");
}else{
	System.out.println("用户名或密码错误");
}

PreparedStatement预编译的SQL执行对象, 在创建对象时将SQL语句中的逻辑判断部分进行了编译
可以理解为将SQL语句中的逻辑部分锁死,只留下?等待将用户输入的内容替换进来
当把?内容替换时 会以值的方式进行处理 不会再对原有SQL语句的逻辑产生影响,从而避免了SQL注入

示例:

/**
 * 登录功能
 */
public class Demo08 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = sc.nextLine();
        System.out.println("请输入密码:");
        String password = sc.nextLine();

        try(Connection conn = DBUtils.getConn()) {
            PreparedStatement ps = conn.prepareStatement("select password from user where username=?");
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();//执行sql语句
            if (rs.next()){
                String pw = rs.getString(1);//获取密码
                if (pw.equals(password)){//判断密码是否正确
                    System.out.println("登录成功!");
                }else{
                    System.out.println("密码错误!");
                }
            }else{
                System.out.println("用户名不存在!");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
/**
 * 改良注册
 */
public class Demo09 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = sc.nextLine();
        System.out.println("请输入密码:");
        String password = sc.nextLine();
        System.out.println("请输入昵称:");
        String nickname = sc.nextLine();

        try(Connection conn = DBUtils.getConn();) {
            //判断输入的用户名是否存在
            PreparedStatement ps = conn.prepareStatement("select count(*) from user where username=?");
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();

            if (rs.next()){
                System.out.println("用户名已存在!请重新输入!");
                return;
            }
            System.out.println("111111");
            //用户名不存在则执行注册流程
            ps = conn.prepareStatement("insert into user values(null,?,?,?) ");
            ps.setString(1,username);
            ps.setString(2,password);
            ps.setString(3,nickname);

            int i = ps.executeUpdate();
            if (i>0){
                System.out.println("注册成功!");
            }else{
                System.out.println("注册失败!");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值