Statement存在两个弊端:
1.存在拼串操作,很繁琐
2.存在Sql注入问题,利用某些系统没有对用户的注入进行充分的检查,而在用户用户输入的数据中注入非法的语句。例如:
SELECT USER,PASSWORD
FROM user_table
WHERE USER='1' OR 'AND password='=1 OR '1'='1''
对于JAVA而言,放置SQL注入,只需要用PreparedStatement替换原有的Statement即可。
利用Statement执行插入操作
package com.chanda.statement.crud;
import com.chanda.connection.ConnectionTest;
import org.junit.Test;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
/**
* @author 禅达啊
* @date 2020/9/22 19:46
*/
public class PreparedStatementUpdate {
/*
* 使用preparedStatement实现对数据表的增删改查操作
* */
//建立连接
//1.增删改
//向customers表中添加一条记录
@Test
public void testInsert() throws Exception
{
//1.读取配置文件中的4个基本信息
InputStream is= ConnectionTest.class.getClassLoader().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");
//2.加载驱动
Class.forName(driverClass);
//3.获取链接
Connection conn= DriverManager.getConnection(url,user,password);
//4.预编译sql语句
String sql="insert into customers(name,email,birth) values(?,?,?)";//?是占位符
PreparedStatement ps=conn.prepareStatement(sql);
//5.填充占位符,注意,索引从1开始
ps.setString(1,"小六子");
ps.setString(2,"321dwad1@qq.com");
SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date=sd.parse("2003-12-03");
ps.setDate(3,new java.sql.Date(date.getTime()));
//6.执行sql
ps.execute();
//7.资源关闭
ps.close();
conn.close();
}
}