文章目录
1. 取得自动增长的主键值
1.1 主键值自动增长
1.在很多使用中,需要取的自动增长的主键值,好方便对数据的操作,就必须保证主键值是自动增长的
2. Oracle中使用序列实现主键值的自动增长
3. mysql中可以在创建数据表的时候就指定主键值自动增长,也可以在工具中修改比如在Navicat中
1.2 取得自动增长的主键值
/取得发送sql语句的对象时,增加参数,取得主键自增长的值
pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
再调用PrepraedStatement对象的getGeneratedKeys()方法,返回封装主键值的ResultSet对象,再从ResultSet对象中取出主键值
ResultSet key = pst.getGeneratedKeys();
/**
* 插入数据,并取的主键自增长的值
* @throws Exception
*/
public static void addEmp() throws Exception{
Connection conn = null;
PreparedStatement pst=null;
try {
//获得连接对象
conn = ConnectionUtil.getConnection();
//准备sql语句
String sql = "insert INTO emp (ename,job,sal,hiredate,mgr,comm,deptno)" + "VALUES('Bob','Cleaner',2000.0,NOW(),7788,null,40)";
//取得发送sql语句的对象,增加参数,取得主键自增长的值
pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
//发送sql语句指令
pst.executeUpdate();
//返回主键自增值
ResultSet key = pst.getGeneratedKeys();
if(key.next()){
System.out.println("主键自增长的值为"+key.getInt(1));
}
}catch (Exception e){
e.printStackTrace();
}finally{
//关闭资源
conn.close();
}
}
-----------------------------
//主方法执行
public class Test01
{
public static void main(String[] args) throws Exception{
addEmp();
}
}
2. 使用占位符
2.1 sql注入风险
sql注入:比如下列这种,就能在没有真实密码的情况下登录账户,非常不安全
2.2 占位符的使用
2.2.1 PreparedStatement接口的特征
PreparedStatement接口的特征:
1. 使用这个接口操作的sql语句会预先编译成指令再发送给数据库,数据库执行该指令,可以在一定程度上提高执行速度。
2. 可以避开sql需要使用字符串拼接的方式拼接在一起,使用占位符(?)来代替原来的字符串拼接,就没有sql注入的风险。
3. 占位符会为字符串自动增加单引号
插入,修改都可以使用占位符,更加安全。
/**
* 占位符的使用,防止sql注入,在修改数据中也可以使用
* @param
* @return
*/
public static boolean perch() throws Exception{
//获取连接
Connection conn = ConnectionUtil.getConnection();
//准备sql语句,值使用占位符
String sql ="INSERT INTO emp (ename,job,sal) VALUES(?,?,?)";
//定义发送sql对象
PreparedStatement pst = null;
try{
//获取发送sql对象
pst=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
//为占位符赋值
pst.setString(1,"Mary");
pst.setString(2,"程序媛");
pst.setDouble(3, 3000.0);
//执行sql语句
return pst.executeUpdate()>0;
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭资源
ConnectionUtil.close(conn,pst);
}
return false;
}
----------------
//主方法调用