赞
踩
(Java DataBase Connectivity)
JDBC是定义了一套数据库的接口,他可以用统一的一套Java代码来操作数据库
我们需要知道以下步骤:
public class JDBCTools { private String url = "jdbc:mysql://localhost:3308/hzyc98"; private String username = "root"; private String userpassword = "mysql"; private Connection conn; private Statement stmt; private ResultSet reSet; //连接的封装方法 private void connect() { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, username, userpassword); stmt = conn.createStatement(); } catch (Exception e) { e.printStackTrace(); } } /** * 操作查询语句,查询到该表之后返回一个集合 * 返回一个类型为:ArrayList<Map<String, String>>的集合 * 一条List代表着一行语句,这一行语句由Map,也就是表头和内容所组成 * * @param sql 一条SQL语句,(select语句) */ public ArrayList<Map<String, String>> query(String sql) { ArrayList<Map<String, String>> rsList = null; try { rsList = new ArrayList<Map<String, String>>(); connect(); reSet = stmt.executeQuery(sql); //获取结果集 ResultSetMetaData rsmd = reSet.getMetaData(); //一个reSet就是火车列表的一行数据。 while (reSet.next()) { Map<String, String> reSetMap = new HashMap<String, String>(); for (int c = 1; c <= rsmd.getColumnCount(); c++) { String columeName = rsmd.getColumnName(c); String value = reSet.getString(columeName); reSetMap.put(columeName, value); } rsList.add(reSetMap); } } catch (Exception e) { e.printStackTrace(); } finally { close(); } return rsList; } //更新数据库,使用stmt载体 public void update(String sql) { try { connect(); stmt.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } finally { close(); } } }
这种方法比较万能,不是将他封装成一个固定的对象,而是将他封装成为一个万能的集合。
public class 练习{ public static void main(String[] args) { List<User> list = new JDBCutil().findAll(); System.out.println(list); } public List<User> findAll() { String sql = "select * from user"; Connection conn = null; Statement stmt = null; ResultSet rs = null; List<User> list = null; try { conn = JDBCUtils.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); User u; list = new ArrayList<>(); while (rs.next()) { u = new User(); u.setId(rs.getString("id")); u.setUname(rs.getString("username")); u.setPwd(rs.getString("password")); list.add(u); } } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.close(rs,stmt,conn); } return list; } }
解决sql注入问题:
引入PreparedStatement
set设置参数 使得sql执行的效率更高。
public class JDBCutil { public static void main(String[] args) throws SQLException { List<User> list = new JDBCutil().findAll("23"); System.out.println(list); } public List<User> findAll(String id) throws SQLException { Connection conn = null; Statement stmt = null; ResultSet rs = null; List<User> list = null; PreparedStatement pstmt; try { conn = JDBCUtils.getConnection(); String sql = "select * from user where id = ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); // stmt = conn.createStatement(); rs = pstmt.executeQuery(); User u; list = new ArrayList<>(); while (rs.next()) { u = new User(); u.setId(rs.getString("id")); u.setUname(rs.getString("username")); u.setPwd(rs.getString("password")); list.add(u); } System.out.println(list); } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.close(rs, stmt, conn); } return list; } }
public class JDBCUtils { private static String url; private static String user; private static String password; private static String dirver; /* * 静态代码块用来加载jdbc中的配置文件 * */ static { try { // Properties集合类 Properties pro = new Properties(); //获取src路径下的文件的方式--->ClassLoader 类加载器 ClassLoader classLoader = JDBCUtils.class.getClassLoader(); URL res = classLoader.getResource("jdbc.properties"); String path = res.getPath(); pro.load(new FileReader(path)); url = pro.getProperty("url"); user = pro.getProperty("user"); password = pro.getProperty("password"); dirver = pro.getProperty("driver"); Class.forName(dirver); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /** * 释放资源 * * @param stmt * @param conn */ public static void close(Statement stmt, Connection conn) { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 释放资源 * * @param stmt * @param conn */ public static void close(ResultSet rs, Statement stmt, Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 获取连接 * * @return 连接对象 */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password); } }
url=jdbc:mysql://localhost:3308/test
user=root
password=mysql
driver=com.mysql.jdbc.Driver
使用Druid+配置文件替代JDBC工具类
public class JDBCUtils { private static DataSource ds; static { try { //1.加载配置文件 Properties pro = new Properties(); pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); //2.获取DataSource(获取连接池对象) ds = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { e.printStackTrace(); } } /** * 获取连接 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } /** * 释放资源 */ public static void close(PreparedStatement stmt, Connection conn) { close(null, stmt, conn); } public static void close(ResultSet rs, PreparedStatement stmt, Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close();//归还连接 } catch (SQLException e) { e.printStackTrace(); } } } /** * 获取连接池方法 */ public static DataSource getDataSource() { return ds; } }
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3308/test
username=root
password=mysql
#初始个数
initialSize=5
maxActive=10
maxWait=3000
Spring JDBC是简化了对类的封装,简化了很多不必要的操作,就是Druid+配置文件+Spring JDBC完成对数据库的简单封装。
通过创建JdbcTemplate对象。依赖于DataSource 连接池:{ JdbcTemplate template = new JdbcTemplate(ds);}
Spring提供的JDBC简单封装
有几个好处:
简化语句,封装程度更搞!
可以将查询结果封装为指定的对象。
需要注意的是:
需要提前配置好JDK,一般这个Spring JDBC只能在Java1.8以上使用,否则会报错:org/springframework/boot/SpringApplication : Unsupported major.minor version 52.0
public class template { private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); public void updatePwd(String id, String newPwd) { String sql = "update user set password = ? where id = ?"; int count = template.update(sql, id, newPwd); System.out.println(count); } public void insert() { String sql = "insert into user(username,password) values (?,?)"; int count = template.update(sql, "23", "2323"); System.out.println(count); } public void delete(String id) { String sql = "delete from user where id = ?"; int count = template.update(sql, id); System.out.println(count); } public void queryForMap() { String sql = "select * from user where id = ? or id = ?"; Map<String, Object> map = template.queryForMap(sql, "10", "12"); System.out.println(map); } public List<Map<String, Object>> queryForList() { String sql = "select * from user"; List<Map<String, Object>> list = template.queryForList(sql); // for (Map<String, Object> stringObjectMap : list) { // System.out.println(stringObjectMap); // } return list; } public List<User> queryForList_User(){ String sql = "select * from user"; List<User> list = template.query(sql, new RowMapper<User>() { public User mapRow(ResultSet rs, int i) throws SQLException { User user = new User(); user.setId(rs.getString("id")); user.setUname(rs.getString("username")); user.setPwd(rs.getString("password")); return user; } }); // for (User ele : list) { // System.out.println(ele); // } return list; } public List<User> queryForList_User_2(){ String sql = "select * from user"; List<User> list = template.query(sql, new BeanPropertyRowMapper<User>(User.class)); // for (User ele : list) { // System.out.println(ele); // } return list; } public void checkCount(){ String sql = "select count(*) from user"; Long total = template.queryForObject(sql, Long.class); System.out.println(total); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。