序列在前面写过有关的博客,也有过总结,但是今天在做一个JDBC操作数据库的相关内容时 需要使用序列创建一个自增长的字段 居然不会了,所以将序列写在本篇的前面
1,序列是一个保存数据连续的增长的一种方式;
序列的创建;
CREATE SEQUENCE seq_pro 2 INCREMENT BY 1 -- 每次加几个 3 START WITH 1 -- 从1开始计数 4 NOMAXVALUE -- 不设置最大值 (MAXVALUE 99999999) 5 NOCYCLE -- 一直累加,不循环 6 CACHE 10;
上述代码就创建好了一个序列,关键是怎么样了使用序列的问题
那个字段需要是连续的就创建序列来做 (seq_pro.nextval);
insert into table_pro values(seq_pro.nextval,'佳','2');
2,单例模式;
简化JDBC对数据库的操作,优化ORACLE数据库,提高性能
思路:将程序的连接写在一个静态类中,程序只能连接一次数据库;返回一个静态的方法
package 单例模式; import java.sql.Connection; import java.sql.DriverManager; public class ConnDB { private static Connection conn = null; private ConnDB() { } public static Connection getCon() { if (conn != null) { return conn; } try { Class.forName("oracle.jdbc.driver.OracleDriver"); String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; conn = DriverManager.getConnection(url, "scott", "tiger"); return conn; } catch (Exception e) { e.printStackTrace(); return null; } } }
2,1jdbc与单例模式
查询;
public void SalAndJOb4eName(String name) { try { Connection conn = ConnDB.getCon(); Statement stm = conn.createStatement(); String sql = "select sal,job from emp where ename='" + name + "'"; System.out.println(sql); ResultSet rs = stm.executeQuery(sql); while (rs.next()) { Float sal = rs.getFloat(1); String job = rs.getString(2); System.out.println(sal + "" + job); } } catch (Exception ef) { ef.printStackTrace(); } }
调用;创建主类
demo.SalAndJOb4eName("SMITH");
运行结果;
select sal,job from emp where ename='SMITH'
800.0CLERK
3,sql注入与预编译
public void SalAndJOb4eName(String name) { try { Connection conn = ConnDB.getCon(); Statement stm = conn.createStatement(); String sql = "select sal,job from emp where ename='" + name + "'"; System.out.println(sql); ResultSet rs = stm.executeQuery(sql); while (rs.next()) { Float sal = rs.getFloat(1); String job = rs.getString(2); System.out.println(sal + "" + job); } } catch (Exception ef) { ef.printStackTrace(); } }
调用;
demo.SalAndJOb4eName("1' or '1'='1");
运行结果;
select sal,job from emp where ename='1' or '1'='1'
800.0CLERK
1600.0SALESMAN
1250.0SALESMAN
2975.0MANAGER
1250.0SALESMAN
2850.0MANAGER
2450.0MANAGER
3000.0ANALYST
5000.0PRESIDENT
1500.0SALESMAN
1100.0CLERK
950.0CLERK
3000.0ANALYST
1300.0CLERK
3,1 预编译可以防止简单点的sql注入问题
思路:先将sql语句编译再赋值;
//预编译的时候要传入sql
psmt.setString(1, name);//赋值
//执行编译的时候不需要传入sql
// 预编译 public void SalAndJob4eName2(String name) { try{ Connection conn = ConnDB.getCon(); //创建sql语句 String sql = "select sal,job from emp where ename=?"; //预编译 PreparedStatement psmt = conn.prepareStatement(sql); //赋值 psmt.setString(1, name); //执行编译 ResultSet rs = psmt.executeQuery(); while (rs.next()) { Float sal = rs.getFloat(1); String job = rs.getString(2); System.out.println(sal + "" + job); } }catch(Exception ef){ ef.printStackTrace(); } }
调用;
demo.SalAndJob4eName2("1' or '1'='1"); //没有结果
demo.SalAndJob4eName2("SMITH");//有一条