(课本P273-任务九)
/**DAO: Data Access Object
* 为什么用: 实现功能的模块化,更有利于代码的维护和升级
* 是什么: 访问数据信息的类,包含对数据的CRUD(create,read,update,delete)
* 怎么写: 使用JDBC编写DAO可能会包含的方法: insert/delete/update/select 操作都可以包含在其中
*/
/*出现的问题总结:
1.设置数据库的主键,主键不可重复;
2.JavaBean的users 中有toString方法,特别适合输出查询的信息;public void showAll(Object[] args){}批量输出users数组的信息.
3.sql时间类使用的方法: ud.insert(new users(1,"admin5","123456","aaa@qq.com",new Date(new java.util.Date().getTime())));
4.创建DAO的测试类,testDAO后, usersDAO ud=new usersDAO(); 实例化,之后实现以下几个简单功能:
添加insert: 传入一个对象user, 添加用户信息: public boolean insert(users user){.......}
查找数据库中的所有的user对象,并返回所有的user对象: public ArrayList<users> findAll(){...}
查找指定的user, 根据id或者username ,返回该对应对象: public users find(String find_name, Object object){ ... }
删除指定的用户,根据id或者username : public boolean delete(String find_name,Object object){...}
修改指定的用户,根据传入的user的对象的所有属性进行全部更新 : public boolean update(users u){...}
*/
1,数据库的设计
1-1 打开数据库,手动启动mysql服务;使用命令行创建数据库jdbc,以及表users
Type 'help;' or '\h' for help. Type '\c' to clear the current input state mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sakila |
| test |
| world |
+--------------------+
6 rows in set (0.04 sec) mysql> create database jdbc;
Query OK, 1 row affected (0.02 sec) mysql> use jdbc;
Database changed
mysql> create table users(
-> id int not null,
-> username varchar(15) ,
-> password varchar(15) ,
-> email varchar(20),
-> birthday date);
Query OK, 0 rows affected (0.16 sec) mysql> desc jdbc;
ERROR 1146 (42S02): Table 'jdbc.jdbc' doesn't exist
mysql> desc uesrs;
ERROR 1146 (42S02): Table 'jdbc.uesrs' doesn't exist
mysql> desc user;
ERROR 1146 (42S02): Table 'jdbc.user' doesn't exist
mysql> desc users;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| username | varchar(15) | YES | | NULL | |
| password | varchar(15) | YES | | NULL | |
| email | varchar(20) | YES | | NULL | |
| birthday | date | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
1-2 创建src下的 jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc
user=root
password=root
2.JavaBean的users
package day_20; import java.sql.Date; public class users {
private int id;
private String username,password,email;
private Date birthday; public users() {
} @Override
public String toString() {
return "users{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", birthday=" + birthday +
'}';
}
public void showAll(Object[] args){
for(int i=0;i<args.length;i++)
System.out.println(args[i].toString());
}
public users(int id, String username, String password, String email, Date birthday) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.birthday = birthday;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
3-编写DAO若干个模块功能: usersDAO
package day_20; import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList; public class usersDAO {
//1.添加insert: 传入一个对象user, 添加用户信息
public boolean insert(users user){
String sql="insert into users(id,username,password,email,birthday) " +
" values(?,?,?,?,?)";
JDBCTools.update_sql(sql,user.getId(),user.getUsername(),user.getPassword(),
user.getEmail(),user.getBirthday());
return true;
}
//2.查找数据库中的所有的user对象,并返回所有的user对象,
public ArrayList<users> findAll(){
Connection connection=null;
Statement statement=null;
ArrayList<users> list=new ArrayList<users>();
ResultSet rs = null;
try {
connection = JDBCTools.getConnection();
statement = connection.createStatement();
String sql="select * from users";
rs = statement.executeQuery(sql);//执行查询操作!
//处理结果集
while(rs.next()){
users user=new users();
user.setId(rs.getInt(1));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString(4));
user.setBirthday(rs.getDate(5));
list.add(user); //加进查询的对象的 结果集
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.release(rs,statement ,connection );
}
return list;
}
//3.查找指定的user, 根据id或者username ,返回该对应对象
public users find(String find_name, Object object){
String sql;
if(find_name=="id"){
sql="select * from users where id = "+(int)object;
}
else{
sql="select * from users where username = '"+object+"'";
}
Connection connection=null;
Statement statement=null; ResultSet rs = null;
try {
connection = JDBCTools.getConnection();
statement = connection.createStatement();
//sql="select * from users";
rs = statement.executeQuery(sql);//执行查询操作!
//处理结果集
while(rs.next()){
users user=new users();
user.setId(rs.getInt(1));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString(4));
user.setBirthday(rs.getDate(5));
return user;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.release(rs,statement ,connection );
}
return null;
}
//4.删除指定的用户,根据id或者username
public boolean delete(String find_name,Object object){
String sql;
if(find_name=="id"){
sql="delete from users where id = ? ";
}
else{
sql="delete from users where username = ? ";
}
JDBCTools.update_sql(sql,object);
return true;
}
//5.修改指定的用户,根据传入的user的对象的所有属性进行全部更新
public boolean update(users u){
String sql;
sql="update users set id=?,username=?,password=?,email=?,birthday=? " +
"where id = ?";
JDBCTools.update_sql(sql,u.getId(),u.getUsername(),u.getPassword(),u.getEmail(),u.getBirthday(),
u.getId());
return true;
} }
4-创建DAO的测试类
/**DAO: Data Access Object
* 为什么用: 实现功能的模块化,更有利于代码的维护和升级
* 是什么: 访问数据信息的类,包含对数据的CRUD(create,read,update,delete)
* 怎么写: 使用JDBC编写DAO可能会包含的方法: insert/update/delete 操作都可以包含在其中
*/
public class testDAO {
@Test //测试创建/增删查改功能!
public void test_DAO(){
// 1.添加insert: 传入一个对象user, 添加用户信息
usersDAO ud=new usersDAO();
ud.insert(new users(1,"admin5","123456","aaa@qq.com",new Date(new java.util.Date().getTime()))); // 3.查找指定的user, 根据id或者username ,返回该对应的唯一的对象
String ans1=(ud.find("id", 3)).toString();
System.out.println(ans1);
ans1=(ud.find("username", "admin5")).toString();
System.out.println(ans1);
// 4.删除指定的用户,根据id或者username
ud.delete("id", 1);
ud.delete("username", "admin2");
// 5.修改指定的用户,根据传入的user对象,先匹配id, 然后对所有属性进行全部更新
ud.update(new users(3,"admin3","598062186","aaa@qq.com",new Date(new java.util.Date().getTime()))); // 2.查找数据库中的所有的user对象,并返回所有的user对象,
ArrayList<users> list = ud.findAll();
new users().showAll(list.toArray());
}
}
5-最终敲定版的JDBCTools 工具类 (使用时注意变更!)
/**操纵JDBC的工具类,其中封装了一些工具方法
* Version 1 : getConnection() : 通过读取配置文件从数据库服务器获取一个连接;
* Version 2 : release() : 关闭数据库资源的ResultSet/Statement/Statement
* Version 3 : update_sql() : 使用preparedStatement实现 :SQL的增删改!
* Version 4: query_sql() : 使用preparedStatement实现 :SQL的select查询! 输出数据库的全部内容
*/
public class JDBCTools {
/*** 执行sql 语句,使用Preparedstatement
*
*/
public static void release(ResultSet rs,Statement statement, Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e2) {
e2.printStackTrace();
}
}
}
public static Connection getConnection() throws Exception{
//1.准备数据库的连接的四个字符串
String driverClass=null,jdbcUrl=null,user=null,password=null;
//jdbc:mysql:///books ;也可以将localhost省略掉!
//2.读取类路径下的jdbc.properties 文件
InputStream in=
JDBCTools.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties =new Properties();
properties.load(in);
driverClass =properties.getProperty("driver");
jdbcUrl=properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
//3.加载数据库驱动程序(注册驱动),driver对应的实现类中有注册驱动的静态代码块
// Class.forName(driverClass); //
//或这么手动加载,也可以注册多个数据库连接的代码块
//DriverManager.registerDriver( Class.forName(driverClass).newInstance()); //4.通过DriverManager 的getConnection()方法获取数据库连接。
Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
System.out.print(connection); //com.mysql.jdbc.JDBC4Connection@19e1023e return connection;
} //使用preparedStatement实现 :SQL的增删改!
public static void update_sql(String sql,Object...args){
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
connection = JDBCTools.getConnection();
preparedStatement=connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
preparedStatement.setObject(i+1, args[i]);
}
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.release(null,preparedStatement ,connection);
}
}
//使用preparedStatement实现 :SQL的select查询! 输出数据库的全部内容
public static void query_sql(String sql,Object...args){
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
connection = JDBCTools.getConnection();
preparedStatement=connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
preparedStatement.setObject(i+1, args[i]);
}
ResultSet resultSet=null;
resultSet=preparedStatement.executeQuery();//执行查询操作!
Boolean flag=true;
while(resultSet.next()){
flag=false;
Map<String,Object> values=new HashMap<String,Object>();
//1. 得到ResultSetMetaData 对象
ResultSetMetaData rsmd = resultSet.getMetaData();
//2.打印每一列的列名
for (int i = 0; i < rsmd.getColumnCount(); i++) {
String columnLabel = rsmd.getColumnLabel(i + 1); //获取列表标签名称
Object columnValue = resultSet.getObject(columnLabel); //根据名称,获取列值,存入HashMap
values.put(columnLabel, columnValue);
}
//System.out.println(values); //获取一组结果 ,重复的键值对会被后面的覆盖掉
// Class clazz = author.class;
// Object object = clazz.newInstance();
System.out.println();
for (Map.Entry<String, Object> entry : values.entrySet()) {
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
System.out.print( fieldName + ":" + fieldValue+"\t");
}
System.out.println();
} if(flag==true)
System.out.println("\n数据表为空或者404!");
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.release(null,preparedStatement ,connection);
}
}
}