JDBC-PreparedStatement实现CURD(笔记)

1.数据库的作用是向数据库服务器发送命令和SQL语句,并接受数据库服务器返回的结果,数据库连接也是Socket连接。

2.在java.sql包中有3个接口分别定义了对数据库的调用的不同方式,由Driver Manager进行管理:
-Statement: 用于执行静态SQL语句,并返回它所生成结果的对象。
-PreparedStatement: SQL语句被预编译,存储在此对象中,可以使用此对象多次高效地执行该语句。
-CallableStatement: 用于执行SQL存储过程

3.使用Statement操作数据表的弊端:
-1 通过调用Connection 对象的 createStatement()方法创建对象,该对象用于执行静态的SQL语句,并且返回执行结果。
-2 Statement 接口中定义了下列方法,用于执行SQL语句:

 int excuteUpdate(String sql):   //执行更新操作 INSERT , UPDATE, DELETE
 ResultSet executeQuery(String sql):  //执行查询操作 SELECT

4.使用Statement 操作数据表存在弊端:
-问题一: 存在拼串操作,繁琐
-问题二: 存在SQL注入问题

  1. SQL 注入是利用某些系统没有对用户输入的数据进行充分的检查,进而在用户输入数据中注入非法的SQL语句或者命令
    (如: SELECT user ,password FROM user_table where user=‘a’ OR 1= ‘AND password = ’ OR ‘1’ = ‘1’ ) , 从而利用系统的SQL 引擎完成恶意操作

6.在Java语言中,要防范SQL注入, 只要用PreparedStatement (从Statement扩展而来) 取代Statement即可

//GetConnection.class
package util;

import PreparedStatementCURD.PreparedStatementTest;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Vodka
 * @date 2021/07//17:14
 */
public class GetConnection {
/*
*    封装获取数据库连接的函数
* */
        public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
            //加载配置文件
            InputStream IS = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
            Properties pros = new Properties();
            pros.load(IS);
            String User = pros.getProperty("User");
            String PassWord = pros.getProperty("PassWord");
            String Url = pros.getProperty("Url");
            String DriverClass = pros.getProperty("DriverClass");

            //利用反射机制,注册驱动,连接数据库
            Class.forName(DriverClass);
            Connection  conn = DriverManager.getConnection(Url,User,PassWord);
            if(conn != null) System.out.println("数据库连接成功!");
            else System.out.println("数据库连接失败!");
//            返回连接
            return conn;
        }


    /*
     *     2.封装关闭流函数
     * */
    public static void Close(Connection conn , PreparedStatement ps) throws SQLException{
        conn.close();
        ps.close();
        if(conn == null && ps == null){
            System.out.println("数据库连接已关闭!");
        }
    }
}




//Test.class
package PreparedStatementCURD;
import util.GetConnection;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;


/**
 * @author Vodka
 * @date 2021/07//17:28
 */
public class Test {
   @org.junit.Test
    public void test(){
      try{
          //使用封装好的连接函数,获取数据库连接
          Connection conn = GetConnection.getConnection();
          String sql = "insert into student (Sno,Sname,Sex,InTime) values(?,?,?,?)";
          PreparedStatement ps =  conn.prepareStatement(sql);
          ps.setString(1,"4550");
          ps.setString(2,"拉水");
          ps.setString(3,"0");
          java.util.Date Times =  new java.util.Date();
          java.sql.Timestamp times = new java.sql.Timestamp(Times.getTime());
          ps.setTimestamp(4, times);

          System.out.println(times);
          //插入数据
          ps.execute();

          //使用封装好的关闭函数,关闭数据库相关连接
          GetConnection.Close(conn ,ps);
      }catch(SQLException e){
          e.printStackTrace();
      } catch(IOException e){
          e.printStackTrace();
      } catch(ClassNotFoundException e){
          e.printStackTrace();
      }

   }

}




















package PreparedStatementCURD;

import org.junit.Test;
import util.GetConnection;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author Vodka
 * @date 2021/07//22:00
 */
public class UpdateTest {
    //更新数据库的测试
    @Test
    public void updateTest(){
        try {
//            //建立数据库连接
//            Connection conn = GetConnection.getConnection();
//            //更新数据
//            String UpdateSQL = "update student set Sname = ? , InTime = ? where Sno =   ?";
//            java.sql.Timestamp time= new java.sql.Timestamp(new java.util.Date().getTime());
//
//            //预编译sql语句
//            PreparedStatement ps =conn.prepareStatement(UpdateSQL);
//           //设置变量值
//            ps.setObject(1,"维迦");
//            ps.setTimestamp(2,time);
//            ps.setString(3,"19125");
//            //执行sql语句
//            ps.execute();
            String Dsql = "delete from student where Sno = ?";    //这里要注意,当表名和数据库关键字重名时,要加单引号,例如`order`
            String Upsql = "update student set Sage = Sage + ? where Sex = ?";
            operation(Upsql, "5" , "1");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //高内聚,低耦合,封装一个curd通用的函数,因为参数是不确定的,所以利用可变参数
    public void operation(String sql , Object ...args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            //建立连接
            conn = GetConnection.getConnection();
            //预编译
            ps = conn.prepareStatement(sql);
            for (int index = 0; index < args.length; index++) {
                ps.setObject(index + 1, args[index]);   //这里要注意两个变量下标起始值的不同
            }
            //执行sql语句
            ps.execute();

        } catch(Exception e){
            e.printStackTrace();
        } finally{
            try{
               if(conn != null && ps != null) GetConnection.Close(conn,ps);
            } catch(SQLException e){
                 e.printStackTrace();
            }

        }
    }

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值