苦尽甘来 一个月学通JavaWeb(三十七 数据库)
夜光序言:
当年年少,老人展翼将尚还是雏 鹰般的少年小心翼翼的庇护……路而 行,雏鹰渐长,如今翱翔九天,鹰翼 之下,无人能再伤迟暮的他
正文:做开发的时候,只要涉及到数据库,肯定需要了解一个JdbcUtils工具类~~
1 那么:JdbcUtils的作用
嗯唔~~
我们也看到了,连接数据库的四大参数是:驱动类、url、用户名,以及密码。
这些参数都与特定数据库关联,如果将来想更改数据库,那么就要去修改这四大参数,那么为了不去修改代码,我们写一个JdbcUtils类,让它从配置文件中读取配置参数,然后创建连接对象。
2 JdbcUtils代码
JdbcUtils.java
public class JdbcUtils { private static final String dbconfig = "dbconfig.properties"; private static Properties prop = new Properties(); static { try { InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(dbconfig); prop.load(in); Class.forName(prop.getProperty("driverClassName")); } catch(IOException e) { throw new RuntimeException(e); } }
public static Connection getConnection() { try { return DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password")); } catch (Exception e) { throw new RuntimeException(e); } } } |
dbconfig.properties
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mydb1?useUnicode=true&characterEncoding=UTF8 username=root password=123456789 |
UserDao
修改项目:
- 把UserDao修改为接口,然后把原来的UserDao修改类名为UserDaoImpl
- 修改UserService中对UserDao的实例化:private UserDao userDao = DaoFactory.getUserDao()
- 创建DaoFactory,提供getUserDao()
1 DAO模式
DAO(Data Access Object)模式就是写一个类,把访问数据库的代码封装起来。DAO在数据库与业务逻辑(Service)之间。
- 实体域,即操作的对象,例如我们操作的表是user表,那么就需要先写一个User类;
- DAO模式需要先提供一个DAO接口;
- 然后再提供一个DAO接口的实现类;
- 再编写一个DAO工厂,Service通过工厂来获取DAO实现。
2 代码
User.java
public class User { private String uid; private String username; private String password; … } |
UserDao.java
public interface UserDao { public void add(User user); public void mod(User user); public void del(String uid); public User load(String uid); public List<User> findAll(); } |
UserDaoImpl.java
public class UserDaoImpl implements UserDao { public void add(User user) { Connection con = null; PreparedStatement pstmt = null; try { con = JdbcUtils.getConnection(); String sql = "insert into user value(?,?,?)"; pstmt = con.prepareStatement(sql); pstmt.setString(1, user.getUid()); pstmt.setString(2, user.getUsername()); pstmt.setString(3, user.getPassword()); pstmt.executeUpdate(); } catch(Exception e) { throw new RuntimeException(e); } finally { try { if(pstmt != null) pstmt.close(); if(con != null) con.close(); } catch(SQLException e) {} } }
public void mod(User user) { Connection con = null; PreparedStatement pstmt = null; try { con = JdbcUtils.getConnection(); String sql = "update user set username=?, password=? where uid=?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, user.getUsername()); pstmt.setString(2, user.getPassword()); pstmt.setString(3, user.getUid()); pstmt.executeUpdate(); } catch(Exception e) { throw new RuntimeException(e); } finally { try { if(pstmt != null) pstmt.close(); if(con != null) con.close(); } catch(SQLException e) {} } }
public void del(String uid) { Connection con = null; PreparedStatement pstmt = null; try { con = JdbcUtils.getConnection(); String sql = "delete from user where uid=?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, uid); pstmt.executeUpdate(); } catch(Exception e) { throw new RuntimeException(e); } finally { try { if(pstmt != null) pstmt.close(); if(con != null) con.close(); } catch(SQLException e) {} } }
public User load(String uid) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtils.getConnection(); String sql = "select * from user where uid=?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, uid); rs = pstmt.executeQuery(); if(rs.next()) { return new User(rs.getString(1), rs.getString(2), rs.getString(3)); } return null; } catch(Exception e) { throw new RuntimeException(e); } finally { try { if(pstmt != null) pstmt.close(); if(con != null) con.close(); } catch(SQLException e) {} } }
public List<User> findAll() { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtils.getConnection(); String sql = "select * from user"; pstmt = con.prepareStatement(sql); rs = pstmt.executeQuery(); List<User> userList = new ArrayList<User>(); while(rs.next()) { userList.add(new User(rs.getString(1), rs.getString(2), rs.getString(3))); } return userList; } catch(Exception e) { throw new RuntimeException(e); } finally { try { if(pstmt != null) pstmt.close(); if(con != null) con.close(); } catch(SQLException e) {} } } } |
UserDaoFactory.java
public class UserDaoFactory { private static UserDao userDao; static { try { InputStream in = Thread.currentThread().getContextClassLoader() .getResourceAsStream("dao.properties"); Properties prop = new Properties(); prop.load(in); String className = prop.getProperty("cn.Genius.jdbc.UserDao"); Class clazz = Class.forName(className); userDao = (UserDao) clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } }
public static UserDao getUserDao() { return userDao; } } |
dao.properties
cn.Genius.jdbc.UserDao=cn.Genius.jdbc.UserDaoImpl |
时间类型
数据库类型与java中类型的对应关系:
DATE à java.sql.Date
TIME à java.sql.Time
TIMESTAMP à java.sql.Timestamp
- 领域对象(domain)中的所有属性不能出现java.sql包下的东西!即不能使用java.sql.Date;
- ResultSet#getDate()返回的是java.sql.Date()
- PreparedStatement#setDate(int, Date),其中第二个参数也是java.sql.Date
时间类型的转换:
- java.util.Date à java.sql.Date、Time、Timestamp
- 把util的Date转换成毫秒值
- 使用毫秒值创建sql的Date、Time、Timestamp
- java.sql.Date、Time、Timestamp à java.util.Date
- 这一步不需要处理了:因为java.sql.Date是java.util.Date;
java.util.Date date = new java.util.Date();
long l = date.getTime();
java.sql.Date sqlDate = new java.sql.Date(l);
1 Java中的时间类型
java.sql包下给出三个与数据库相关的日期时间类型,分别是:
- Date:表示日期,只有年月日,没有时分秒。会丢失时间;
- Time:表示时间,只有时分秒,没有年月日。会丢失日期;
- Timestamp:表示时间戳,有年月日时分秒,以及毫秒。
这三个类都是java.util.Date的子类。
2 时间类型相互转换
把数据库的三种时间类型赋给java.util.Date,基本不用转换,因为这是把子类对象给父类的引用,不需要转换。
java.sql.Date date = …
java.util.Date d = date;
java.sql.Time time = …
java.util.Date d = time;
java.sql.Timestamp timestamp = …
java.util.Date d = timestamp;
当需要把java.util.Date转换成数据库的三种时间类型时,这就不能直接赋值了,这需要使用数据库三种时间类型的构造器。java.sql包下的Date、Time、TimeStamp三个类的构造器都需要一个long类型的参数,表示毫秒值。
创建这三个类型的对象,只需要有毫秒值即可。我们知道java.util.Date有getTime()方法可以获取毫秒值,那么这个转换也就不是什么问题了。
java.utl.Date d = new java.util.Date();
java.sql.Date date = new java.sql.Date(d.getTime());//会丢失时分秒
Time time = new Time(d.getTime());//会丢失年月日
Timestamp timestamp = new Timestamp(d.getTime());
3 代码
我们来创建一个dt表:
CREATE TABLE dt( d DATE, t TIME, ts TIMESTAMP ) |
下面是向dt表中插入数据的代码:
@Test public void fun1() throws SQLException { Connection con = JdbcUtils.getConnection(); String sql = "insert into dt value(?,?,?)"; PreparedStatement pstmt = con.prepareStatement(sql);
java.util.Date d = new java.util.Date(); pstmt.setDate(1, new java.sql.Date(d.getTime())); pstmt.setTime(2, new Time(d.getTime())); pstmt.setTimestamp(3, new Timestamp(d.getTime())); pstmt.executeUpdate(); } |
下面是从dt表中查询数据的代码:
@Test public void fun2() throws SQLException { Connection con = JdbcUtils.getConnection(); String sql = "select * from dt"; PreparedStatement pstmt = con.prepareStatement(sql); ResultSet rs = pstmt.executeQuery();
rs.next(); java.util.Date d1 = rs.getDate(1); java.util.Date d2 = rs.getTime(2); java.util.Date d3 = rs.getTimestamp(3);
System.out.println(d1); System.out.println(d2); System.out.println(d3); } |