PreparedStatement 与 Statement 区别?
1.使用statement执行sql,是以字符串拼接的方式,这时候存在sql注入的风险 名词解释:sql注入---一些非法分子,将一些特殊的字符串,通过字符串拼接的方式注入到系统原有的sql命令中,改变sql的运行逻辑,从而威胁到时据库数据的安全,这种现象就叫做sql注入。 2.使用PreparedStatement 可以避免sql注入问题 3.使用PreparedStatement可以提高程序的可读性、可维护性。
jdbc连接数据库 版本1 createStatement
利用 createStatement 针对于 增删改 dml //jdbc连接数据库 最原始版本1 对于异常进行抛出 public class Test1 { public static void main(String[] args) throws ClassNotFoundException, SQLException { //1. 加载驱动jar:将实现类加载到内存中(JVM) Class.forName ("oracle.jdbc.OracleDriver"); //2.创建数据库连接 url:同一资源定位符--在互联网中,获取到某一个资源的方式 Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr"); //3.书写sql语句 添加一条数据 String sql = "insert into user1 values(2,'bb')"; //4.创建发送sql语句的对象 Statement statement = conn.createStatement (); //5.发送sql语句 int i = statement.executeUpdate (sql); System.out.println ("受影响的行数="+i); //6.关闭资源 先打开的后关闭 if (statement!=null){ statement.close ();} if (conn!=null){ conn.close ();} } }
jdbc 连接数据库 版本2 createStatement
利用 createStatement 针对于 查 dql //查询 对于异常进行 try{}catch(){}finally{} public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName ("oracle.jdbc.OracleDriver"); String url = "jdbc:oracle:thin:@localhost:1521:xe"; String user = "hr"; String password = "hr"; connection = DriverManager.getConnection (url, user, password); //属性 作为条件 ,传入 sql 语句 ,单引号,双引号,++ String c_name = "ss"; String sql = "select * from user1 where c_name = '"+c_name+"'"; statement = connection.createStatement (); resultSet = statement.executeQuery (sql); //System.out.println (i); // 处理结果集 while (resultSet.next ()){ int c_id = resultSet.getInt ("c_id"); String c_name1 = resultSet.getString ("c_name"); System.out.println (c_id+"的名称是:"+c_name1); } } catch (ClassNotFoundException e) { e.printStackTrace (); } catch (SQLException e) { e.printStackTrace (); } finally { try { if (resultSet != null){ resultSet.close ();} if (statement != null){ statement.close (); } if (connection !=null){ connection.close ();} } catch (SQLException e) { e.printStackTrace (); } } } }
jdbc连接数据库 版本3 prepareStatement针对于
利用 prepareStatement针对于 增删改 dml //以 增 为例 public static void addbook(){ Connection connection = null; PreparedStatement preparedStatement = null; try { //加载 驱动jar Class.forName ("oracle.jdbc.OracleDriver"); //获取 数据库 连接 String url = "jdbc:oracle:thin:@localhost:1521:xe"; String user = "hr"; String password = "hr"; connection = DriverManager.getConnection (url, user, password); //书写 sql 语句 String sql = "insert into book values (bookId.nextval,?,?,?,?)"; //创建 发送 sql 语句 的 对象 preparedStatement = connection.prepareStatement (sql); //给 参数 绑定 值 //书名 preparedStatement.setString (1,"ddd"); //价格 preparedStatement.setDouble (2,66.6); //出版日期 // 定义 一个 字符串 类型 的 日期 String str = "1999-12-25"; //定义日期类型 SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd"); //将 字符串 类型 转为 util date Date parse = sdf.parse (str); // 将 util date 转换为 sql date long time = parse.getTime (); //创建 一个 sql dete java.sql.Date sqldate = new java.sql.Date (time); //将处理好的日期 增加 到 程序中 preparedStatement.setDate (3,sqldate); //添加 图书 描述 preparedStatement.setString (4,"这是一本好书"); // 发送 sql 语句 int i = preparedStatement.executeUpdate (); System.out.println ("受影响的行数="+i); } catch (ClassNotFoundException e) { e.printStackTrace (); } catch (SQLException e) { e.printStackTrace (); } catch (ParseException e) { e.printStackTrace (); } finally { //关闭资源 try { if (preparedStatement !=null){ preparedStatement.close (); } if (connection!=null){ connection.close (); } } catch (SQLException e) { e.printStackTrace (); } } }
jdbc连接数据库 版本4 prepareStatement
利用 prepareStatement针对于 查询dql // 区间查询 public static List<Book> getBooksByPriceRange(double minPrice, double maxPrice) { Connection conn = null; PreparedStatement pstmt = null; ResultSet re = null; try { // 加载 驱动 jar Class.forName ("oracle.jdbc.OracleDriver"); //获取 数据库 连接 String url = "jdbc:oracle:thin:@localhost:1521:xe"; String user = "hr"; String password = "hr"; conn = DriverManager.getConnection (url, user, password); //准备 sql 语句 String sql = "select * from book where price between ? and ?"; //准备 发送 sql 语句 的 对象 pstmt = conn.prepareStatement (sql); // 给参数绑定值 pstmt.setDouble (1, minPrice); pstmt.setDouble (2, maxPrice); //发送sql 语句 re = pstmt.executeQuery (); List<Book> books = new ArrayList<Book>(); //处理结果集 while (re.next ()) { int bookId = re.getInt ("bookId"); String bookName = re.getString ("bookName"); double price = re.getDouble ("price"); Date crTime = re.getDate ("crTime"); String describe = re.getString ("describe"); //创建 book 实体类 Book book = new Book (); book.setBookId (bookId); book.setBookName (bookName); book.setPrice (price); book.setCrTime (crTime); book.setDescribe (describe); //将 book 对象 添加 到 集合 中 books.add (book); } return books; } catch (Exception e) { e.printStackTrace (); } finally { try { if (re != null) { re.close (); } if (pstmt != null) { pstmt.close (); } if (conn != null) { conn.close (); } } catch (SQLException e) { e.printStackTrace (); } } return null; }
jdbc连接数据库 版本5 prepareStatement
// 模糊查询 public static List<Book> getBooksByPriceRange1(String like) { Connection conn = null; PreparedStatement pstmt = null; ResultSet re = null; try { // 加载 驱动 jar Class.forName ("oracle.jdbc.OracleDriver"); //获取 数据库 连接 String url = "jdbc:oracle:thin:@localhost:1521:xe"; String user = "hr"; String password = "hr"; conn = DriverManager.getConnection (url,user,password); //准备 sql 语句 String sql = "select * from book where bookName like ?"; //准备 发送 sql 语句 的 对象 pstmt = conn.prepareStatement (sql); // 给参数绑定值 pstmt.setString (1, "%"+like+"%"); //发送sql 语句 re = pstmt.executeQuery (); List<Book> books = new ArrayList<Book>(); //处理结果集 while (re.next ()) { int bookId = re.getInt (1); String bookName = re.getString (2); double price = re.getDouble (3); Date crTime = re.getDate (4); String describe = re.getString (5); Book book = new Book (); book.setBookId (bookId); book.setBookName (bookName); book.setPrice (price); book.setCrTime (crTime); book.setDescribe (describe); //将 book 对象 添加 到 集合 中 books.add (book); } return books; } catch (Exception e) { e.printStackTrace (); } finally { try { if (re != null) { re.close (); } if (pstmt != null) { pstmt.close (); } if (conn != null) { conn.close (); } } catch (SQLException e) { e.printStackTrace (); } } return null; }
jdbc.properties 小配置文件
driver = oracle.jdbc.OracleDriver url =jdbc:oracle:thin:@localhost:1521:xe user = hr password =hr
jdbc 工具类使用 封装的工具类
package busywork.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Properties; public class JDBCUtil { //绑定线程 public static ThreadLocal<Connection> tr = new ThreadLocal<Connection>(); private static Properties p = new Properties(); //用输入流 读入配置文件 static{ //读入配置文件 /*1.map 接口 实现类 Hashtable 类的 子类 properties 类 中的getResourceAstream() 的方法 将配置文件作为参数传入 保存配置信息*/ /* 通过调用properties中的load()方法,可以将.properties结尾文件中的value自动的转换为properties 类中的key, 以properties结尾文件中的value自动转换成properties类中的value */ //2.读入properties try(InputStream is =JDBCUtil.class.getResourceAsStream("/jdbc.properties")){ p.load(is); Class.forName(p.getProperty("driver")); }catch(Exception e){ e.printStackTrace(); } } //创建链接 public static Connection getConnection(){ Connection conn = null; try { conn = DriverManager.getConnection(p.getProperty("url"),p.getProperty("user"),p.getProperty("password")); } catch (Exception e) { e.printStackTrace(); } return conn; } //关闭资源 针对于 dml 增删改 运用方法重载 public static void close(Connection conn,PreparedStatement pstmt){ if(pstmt!=null){ try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } //关闭资源 针对 dml 查 重载close方法 public static void close(Connection conn,PreparedStatement patmt,ResultSet re){ if(re!=null){ try { re.close(); } catch (SQLException e) { e.printStackTrace(); } } if(patmt!=null){ try { patmt.close(); //解除线程 tr.remove(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); //解除线程 tr.remove(); } catch (SQLException e) { e.printStackTrace(); } } } //封装工具栏 日期转换 //将 String 类型转换为 java.util.Date 类型 public static java.util.Date UtilDate(String str){ //定义日期格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy- MM-dd"); try { java.util.Date utilDate = sdf.parse(str); return utilDate; } catch (ParseException e) { e.printStackTrace(); } return null; } //java.util.Date 转换成java.sql.Date public static java.sql.Date toSqlDate(java.util.Date utilDate){ //获取时间戳 long time = utilDate.getTime(); java.sql.Date sqlDate = new java.sql.Date(time); return sqlDate; } }
jdbc连接数据库 版本6 prepareStatement 利用 JDBCUtil工具类开发
在 prepareStatement 的基础上 利用 JDBCUtil工具类 针对于 增删改 dml 进行开发 //增 public void addbook(){ Connection conn = null; PreparedStatement pstmt = null; try { //创建数据库连接 conn = JDBCUtil.getConnection (); // 书写 sql 语句 String sql = "insert into book values (bookId.nextval,?,?,?,?)"; //创建 发送 sql 语句 的对象 pstmt = conn.prepareStatement (sql); // 给参数绑定值 pstmt.setString (1,"是是是"); pstmt.setDouble (2,99.9); pstmt.setDate (3,JDBCUtil.toSqlDate (new java.util.Date ())); pstmt.setString (4,"好好好"); //发送 int i = pstmt.executeUpdate (); System.out.println ("受影响的行数="+i); } catch (Exception e) { e.printStackTrace (); } finally { //关闭资源 JDBCUtil.close(conn, pstmt); } }
jdbc连接数据库 版本7 prepareStatement 利用 JDBCUtil工具类开发
// 查 模糊查询 public List<Book> queryAllBooks(String likebook){ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; ArrayList<Book> books = new ArrayList<Book> (); Book book = null; try { //加载驱动 获取数据库连接 conn = JDBCUtil.getConnection (); //书写 sql 语句 String sql = "select * from book where bookName like ?"; //创建 发送 sql 语句 的对象 pstmt = conn.prepareStatement (sql); // 给参数绑定值 pstmt.setString (1,"%"+likebook+"%"); //发送 sql 语句 rs = pstmt.executeQuery (); //处理结果集 while (rs.next ()){ book = new Book (rs.getInt (1),rs.getString (2),rs.getDouble (3),rs.getDate (4),rs.getString (5)); // 将 book 对象 放到集合中 books.add (book); } return books; } catch (Exception e) { e.printStackTrace (); } finally { JDBCUtil.close (conn,pstmt,rs); } return null; }