JDBC(其二)操作

Statement类

在连接建立后,需要对数据库进行访问,执行命名或是sql语句,可以通过:

  • Statement【存在SQL注入风险】
  • PreparedStatement【预处理】
  • CallableStatement【存储过程】

SQL注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句段或命令,恶意攻击数据库。sql_injection.sql

要防范SQL注入,只要用 PreparedstatementStatemens木)以代 Statement就可以了

ResultSet(结果集)

1.表示数据库结果集的数据表,通常通过执行查询数据库的语句生成
2. ResultSet对象保持一个光标指向其当前的数据行。最初,光标位于第一行之前
3. next方法将光标移动到下一行,并且由于在ResultSet对象中没有更多行时返回false,因此可以在while循环中使用循环来遍历结果集
4. previous()向上移动一行
5. getXxx(列索引/列名)
6. getObject(列索引/列名)

在连接数据库之后,我们可以进行查询数据库的表中数据:

//得到Statement
        Statement statement = connection.createStatement();
        //组织sql语句
        String sql = "select * from emp";
        //执行sql语句返回结果集对象
        ResultSet resultSet = statement.executeQuery(sql);
        //使用while取出数据
        while(resultSet.next()){//让光标向后移动,如果没有更多行,返回false
            int empno = resultSet.getInt(1);
            String ename = resultSet.getString(2);
            String job = resultSet.getString(3);
            System.out.println(empno+"   "+ename+"  "+job);
        }
        resultSet.close();
        statement.close();
        connection.close();

PrepareStatement类

1、 PreparedStatement 执行的SQL语句中的参数用问号(?)来表示,调用
PreparedStatement 对象的setXxx()方法来设置这些参数. setXxx()方法有
两个参数,第一个参数是要设置的SQL语句中的参数的索引(从1开始),第二个是设置的SQL语句中的参数的值

2、调用executeQuervO),返回ResultSet 对象

3、调用executeUpdate():执行更新,包括增、删、修改,返回影响行数

优点:

  • 不再使用+拼接sql语句减少语法错误
  • 有效解决了sql注入问题
  • 大大减少了编译次数,效率较高

在这里插入图片描述使用PreparedStatement安全登录

public static void funConnect05() throws SQLException, ClassNotFoundException, IOException {
        //通过properties对象获取配置文件信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");

        Scanner reader = new Scanner(System.in);
        System.out.println("输入用户名:");
        String user_name = reader.nextLine();
        System.out.println("输入密码:");
        String user_password = reader.nextLine();
        //反射机制加载Driver
        Class.forName(driver);

        Connection connection = DriverManager.getConnection(url,user,password);
        //组织sql语句
        String sql = "select user_name,user_password from user_information"
               + " where user_name=? and user_password=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setString(1,user_name);
        preparedStatement.setString(2,user_password);
        //执行sql语句返回结果集对象
        ResultSet resultSet = preparedStatement.executeQuery();
        //使用while取出数据
        if(resultSet.next()){//让光标向后移动,如果没有更多行,返回false
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }

JDBC API

在这里插入图片描述

JDBCUtils工具类

为了节省资源,提高效率,我们连接数据库可以使用一个类来操作数据库,这样使用数据库时调用此类就可以高效连接数据库。

package utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
	
	//使用静态代码块,一次连接多次使用
    static {
        try {
            init();
        } catch (IOException e) {
            //将编译时异常转换为运行异常
            //可以捕获该异常也可以默认处理
            throw new RuntimeException(e);
        }
    }

	//初始化连接数据
    public static void init() throws IOException {
        //获得初始化参数
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        url = properties.getProperty("url");
        user = properties.getProperty("user");
        password = properties.getProperty("password");
        driver = properties.getProperty("driver");
    }

	//使用连接函数,外接使用连接时直接Connection connection=JDBCUtils.getconnection();
    public static Connection getconnection() {
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

	//关闭资源函数
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}

使用JDBCUtils类:

import java.sql.*;

public class JDBCUtilsTest {
    public static void main(String[] args) {
        Connection connection = null;
        String sql = "insert into userdata values (null,'rick','123')";
        PreparedStatement preparedStatement = null;
        try {
            connection=JDBCUtils.getconnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate();
        }catch(SQLException e){
            e.printStackTrace();
        }
        JDBCUtils.close(null,preparedStatement, connection);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值