jdbcDao 具体实现增删改查层

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 利用 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 利用 JDBCUtil工具类开发

 在 prepareStatement 的基础上 利用  JDBCUtil工具类 针对于 增查 dql 进行开发
 
// 查  模糊查询
    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;
    }

jdbc连接数据库 版本8 对dao层进行封装用junit测试类 进行测试

ORM 对象关系映射,DAO 数据访问对象
对dao层进行封装,用junit测试类 进行测试
1.封装实体类
import java.util.Date;
public class Book {
   private Integer bookId;
   private String bookName;
   private double price;
   private Date crTime;
   private String describe;
  //无参/有参
  //get/set
  //toString()
}

2.定义dao实体类对应的接口
public interface BookDao {
    // 增
    public void addBook(Book book);
    //删
    public void deleteBookById(Integer bookId);
    //改
    public void updateBookById(Book book);
    //根据 id 查询 一个 对象
    public Book selectBookById(Integer bookId);
    //模糊查询
    public List<Book> selectBookLike(String likebookName);
    }

3.实现dao实体类对应的接口中的方法
 public class BookDaoImpl implements BookDao{
    //增
    @Override
    public void addBook(Book book) {
        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,book.getBookName ());
            pstmt.setDouble (2,book.getPrice ());
            pstmt.setDate (3, new java.sql.Date(book.getCrTime ().getTime ()));
            pstmt.setString (4,book.getDescribe ());
            // 发送sql语句
            int i = pstmt.executeUpdate ();
            System.out.println ("受影响的条数是:"+i);
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
            JDBCUtil.close (conn,pstmt);
        }
    }
    //删
    @Override
    public void deleteBookById(Integer bookId) {
        Connection conn=null;
        PreparedStatement pstmt = null;
        try {
            // 加载驱动 获取数据库连接
            conn = JDBCUtil.getConnection ();
            //书写 sql 语句
            String sql = "delete from book where bookId = ?";
            // 创建发送sql语句的对象
             pstmt = conn.prepareStatement (sql);
             //给参数动态绑定值
            pstmt.setInt (1,bookId);
            //发送 sql
            int i = pstmt.executeUpdate ();
            System.out.println ("受影响的行数是="+i);
        } catch (SQLException e) {
            e.printStackTrace ();
        } finally {
            JDBCUtil.close (conn,pstmt);
        }
    }
    //改
    @Override
    public void updateBookById(Book book) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
             conn = JDBCUtil.getConnection ();
            String sql = "update book set bookName=?,price=?,crTime = ?,describe =? where bookId=?";
            pstmt = conn.prepareStatement (sql);

            pstmt.setString (1,book.getBookName ());
            pstmt.setDouble (2,book.getPrice ());
            pstmt.setDate (3,JDBCUtil.toSqlDate (book.getCrTime ()));
            pstmt.setString (4,book.getDescribe ());
            pstmt.setInt (5,book.getBookId());

            int i = pstmt.executeUpdate ();
            System.out.println ("受影响的行数是:"+i);

        } catch (SQLException e) {
            e.printStackTrace ();
        } finally {
            JDBCUtil.close (conn,pstmt);
        }
    }
    
    //根据 bookId 查询 返回一个对象
    @Override
    public Book selectBookById(Integer bookId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet re = null;
        Book book1 = null;
        try {
            conn = JDBCUtil.getConnection ();
            String sql = "select * from book where bookId = ?";
            pstmt = conn.prepareStatement (sql);
            pstmt.setInt (1,bookId);
            re = pstmt.executeQuery ();
            //处理结果集
            if (re.next ()){//返回一个对象 用 if
              book1 = new Book ();
                book1.setBookId (re.getInt ("bookId"));
                book1.setBookName (re.getString ("bookName"));
                book1.setPrice (re.getDouble ("price"));
                book1.setCrTime (re.getDate ("crTime"));
                book1.setDescribe (re.getString ("describe"));
            }
            return book1;
        } catch (SQLException e) {
            e.printStackTrace ();
        } finally {
            JDBCUtil.close (conn,pstmt,re);
        }
        return null;
    }
    // 模糊查询
    @Override
    public List<Book> selectBookLike(String likebookName) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet re = null;
        ArrayList<Book> books = null;
        Book book = null;
        try {
            conn = JDBCUtil.getConnection ();
            String sql = "select * from book where bookName like ?";
            pstmt = conn.prepareStatement (sql);
            pstmt.setString (1,"%"+likebookName+"%");
            re = pstmt.executeQuery ();
            books = new ArrayList<> ();
            //处理结果集
            while (re.next ()){返回多个对象,一个集合 用 while
                book = new Book ();
                book.setBookId (re.getInt ("bookId"));
                book.setBookName (re.getString ("bookName"));
                book.setPrice (re.getDouble ("price"));
                book.setCrTime (re.getDate ("crTime"));
                book.setDescribe (re.getString ("describe"));
               books.add (book);
            }
            return books;
        } catch (SQLException e) {
            e.printStackTrace ();
        } finally {
            JDBCUtil.close (conn,pstmt,re);
        }
        return null;
    }
}

4.junit Test 测试类分别测试
import busywork.entity.Book;
import busywork.util.JDBCUtil;
import org.junit.Test;
import java.util.List;

public class BookTest {
    //作为成员变量
    BookDao dao = new BookDaoImpl ();
    //增加
    @Test
    public void test1(){
        BookDao dao = new BookDaoImpl ();
        Book book = new Book ();
        book.setBookName ("将军在上");
        book.setPrice (66.6);
        String date = "1999-12-23";
        book.setCrTime (JDBCUtil.UtilDate (date));
        book.setDescribe ("花木兰转世");
        dao.addBook (book);
    }

    //删
    @Test
    public void test2(){
        dao.deleteBookById (8);
    }
    //改
    @Test
    public void test3(){
        Book book = new Book ();
        book.setBookId (4);
        book.setBookName ("几度夕阳红");
        book.setPrice (88.8);
        book.setCrTime (JDBCUtil.UtilDate ("2018-12-25"));
        book.setDescribe ("像一首老歌");
        dao.updateBookById (book);
    }

    // 查 结果为一个对象
    @Test
    public void test4(){
        Book book = dao.selectBookById (13);
        System.out.println (book);
    }
    // 查 结果为多条对象 一个集合
    @Test
    public void test5(){
        List<Book> books = dao.selectBookLike ("嬛");
        for (Book book : books) {
            System.out.println (book);
        }
    }
}

用jdbc获取表格数据的总条数 3种方式

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
 
import com.mysql.jdbc.Statement;
 
public class MySQLDao {
 public static void main(String[] args) {
	try {
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
		Statement sta = (Statement) conn.createStatement(ResultSet.CONCUR_READ_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE);
		String sql = "select * from homework";
		ResultSet rs  =sta.executeQuery(sql);
		rs.last();
		System.out.println("行数:"+rs.getRow());
		//如果后面需要遍历
		rs.first();//将指针移动到第一行
		//第二种方法:
		int count=1;//由于rs.first()已经在第一个位置了,而下面的循环又调用了next(),所以此处count从1开始
		while(rs.next()){
			count++;
		}
		System.out.println("行数:"+count);
	//第三种方法:
	 	sql = "select count(*) from homework";
	 	rs = sta.executeQuery(sql);
		rs.next();
		int row = rs.getInt(1);
		System.out.println("行数:"+row);
		conn.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值