您的位置:首页 > 其它

JDBC 实现 含参的增删改查操作

2016-08-02 17:54 405 查看
构建数据库数据的 MySQL 代码

tbl_usercreate table tbl_user(
id int(11) unsigned not null auto_increment,
name varchar(50) not null default '',
password varchar(50) not null default '',
email varchar(50) default '',
primary key (id))
engine = InnoDB
default charset = utf8;

create table tbl_address(
id int(11) unsigned not null auto_increment,
city varchar(20) default null,
country varchar(20) default null,
user_id int(11) unsigned not null,
primary key(id))
engine = innodb
default charset = utf8;

insert into tbl_user(id,name,password,email) values
(1,'xiaoming','123456','xiaoming@gmail.com'),
(2,'xiangzhang','123456','xiaozhang@gmail.com');

insert into tbl_address (city,country,user_id) values
('beijing','china',1);

insert into tbl_address (city,country,user_id) values
('tianjin','china',2);


DTO 类即,Data Transform Object 类,用于需要大量传输的被远程调用的对象数据,它一般对应于数据库中的数据表。

DTO 类一般只包含成员变量以及成员变量的 get、set 方法,DTO 类不包含业务逻辑。

所有的表都含有一个没有业务逻辑的主键 id ,id 的实体类实现对业务类主键信息的封装 。

package EntityPack;

public class IdEntity {
// 所有表都有一个包含无业务含义的主键
// 本类 封装了 业务类的主键信息
private Long id;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

}
package EntityPack;

public class UserEntity extends IdEntity{

private String name;
private String password;
private String email;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}

@Override
public String toString() {
return "UserEntity [name=" + name + ", password=" + password + ", email=" + email + ", getId()=" + getId()
+ "]";
}

}
package EntityPack;

public class AddrEntity extends IdEntity{

private String city;
private String country;
private Long userId;

public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}

@Override
public String toString() {
return "AddrEntity [city=" + city + ", country=" + country + ", userId=" + userId + ", getId()=" + getId()
+ "]";
}

}


DAO 类,即 Dataa Access Object 类,数据访问对象类一般用来封装 对数据库的访问,通过 DAO 可以将数据库中的表转换为 DTO 类。

DAO 接口类

package DaoPack;

import java.sql.Connection;
import EntityPack.UserEntity;

public interface UserDao {

public void save(Connection connection,UserEntity user)throws Exception;
public void update(Connection connection,UserEntity user,Long id)throws Exception;
public void delete(Connection connection,UserEntity user)throws Exception ;

}
DAO 接口类的实现类

package ImplPack;

import java.sql.Connection;
import java.sql.PreparedStatement;

import DaoPack.UserDao;
import EntityPack.UserEntity;

public class UserImpl implements UserDao {

// 保存用户信息
@Override
public void save(Connection connection, UserEntity user) throws Exception {
// TODO Auto-generated method stub
PreparedStatement ps = connection.prepareCall("INSERT INTO tbl_user"
+ "(name,password,email)VALUES(?,?,?)");
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());

ps.execute();
}

// 更新用户信息
@Override
public void update(Connection connection, UserEntity user, Long id) throws Exception {
// TODO Auto-generated method stub
PreparedStatement ps = connection.prepareStatement("UPDATE tbl_user SET name = ?, "
+ "password = ?, email = ? WHERE id = ?");

ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
ps.setLong(4,id);

ps.execute();
}

// 删除用户信息
@Override
public void delete(Connection connection, UserEntity user) throws Exception {
// TODO Auto-generated method stub
PreparedStatement ps = connection.prepareStatement("DELETE FROM tbl_user WHERE id = ?");

ps.setLong(1, user.getId());

ps.execute();
}

}


含参的 JDBC 操作

package TestPack;

import java.sql.Connection;

import DaoPack.UserDao;
import EntityPack.UserEntity;
import ImplPack.UserImpl;
import PropertyConfigPack.ConnectionFactory;

public class UserTestCls {
public static void main(String[] args) {
Connection connection = null;
try {
connection = ConnectionFactory.getInstance().makeConnection();
connection.setAutoCommit(false);

// 创建 DAO
UserDao userDao = new UserImpl();
// 创建用户实体
UserEntity Tom = new UserEntity();
Tom.setEmail("tom@gmail.com");
Tom.setName("Tom");
Tom.setPassword("123456");
// 保存用户实体
userDao.save(connection, Tom);
// 提交事务
connection.commit();
} catch (Exception e1) {
// TODO: handle exception
try {
// 如果出现异常,进行事务的回滚
connection.rollback();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}


查询代码段

// 数据库连接操作
Class.forName(DBDRIVER) ;
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
// 可以查询的得到匹配的 会输出最终结果
// 得不到匹配的 会使得到结果为空
String sql = "SELECT name FROM user WHERE userid = ? AND password = ?";
pstmt = conn.prepareStatement(sql);  // pstmt 实例化
pstmt.setString(1,request.getParameter("id"));
pstmt.setString(2,request.getParameter("pwd"));
rs = pstmt.executeQuery() ;// 执行查询 语句
if(rs.next()){ // 如果有数据,则可以执行
flag = true; // 表示登陆成功
name = rs.getString(1);
}
}catch(Exception e){
System.out.println(e.getMessage());
}
finally{
try{
rs.close();
pstmt.close();
conn.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
// flag 表示登陆成功 或者 失败 此处 显示 登陆跳转逻辑
if(flag){ // 成功
// 下面是标签指令 标签指令必须写在 SCRIPT 之外
%>
<jsp:forward page = "login_success.jsp">
<jsp:param name = "uname" value = "<%=name%>"/>
</jsp:forward>
<%
}else{ // 失败
%>
<jsp:forward page = "login_failure.jsp"/>
<%
}
%>


配置文件报错

Tue Aug 02 17:00:34 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
解决方案,配置文件修改为

driver = com.mysql.jdbc.Driver
dburl = jdbc\:mysql\://localhost\:3306/jsp_db?characterEncoding=utf8&useSSL=false
user = root
password = 1233211234567
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐