######后台成功添加数据,但是数据库信息没有显示
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.sdp.dao;
import edu.sdp.model.Readers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* 读者的数据访问层代码,实现对读者数据的增删改查
*
* @author Administrator
*/
public class ReadersDao {
private Connection conn;
private PreparedStatement pstm;
private ResultSet rs;
private String url = "jdbc:mysql://localhost:3306/SDPLibraryData?useUnicode=true&characterEncoding=utf-8";
private String user = "root";
private String password = "root";
public ReadersDao() {
try {
//初始化数据库连接对象conn
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException ex) {
Logger.getLogger(ReadersDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int add(Readers model) {
int n = -1;
try {
//数据库连接对象,正常是支持自动提交的,如果想启动事物,需要关闭它
conn.setAutoCommit(false);
String sql = "insert into Concats "
+ "(RealName,Sex,Birthday,Mobile,Address,StateId)"
+ " values "
+ "(?,?,?,?,?,?)";
pstm = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
//参数化数据
pstm.setString(1, model.getRealName());
pstm.setString(2, model.getSex());
pstm.setDate(3, model.getBirthday());
pstm.setString(4, model.getMobile());
pstm.setString(5, model.getAddress());
pstm.setInt(6, model.getStateId());
//执行SQL语句并获取影响行数
n = pstm.executeUpdate();
if (n > 0) {
//获取刚刚插入的记录的主键--begin
int concatId = -1;
ResultSet rs = pstm.getGeneratedKeys();
if (rs.next()) {
concatId = rs.getInt(1);
}
System.out.println("联系人编号:" + concatId);
rs.close();
//获取刚刚插入的记录的主键---end
sql = "insert into Readers "
+ "(ReaderNumber,ConcatId,BorrowNumber,BorrowDays,StateId)"
+ " values "
+ "(?,?,?,?,?)";
pstm = conn.prepareStatement(sql);
//参数化数据
pstm.setString(1, model.getReaderNumber());
pstm.setInt(2, concatId);
pstm.setInt(3, model.getBorrowNumber());
pstm.setInt(4, model.getBorrowDays());
pstm.setInt(5, model.getStateId());
n = pstm.executeUpdate();
conn.commit();//手动提交(结束事物)
} else {
System.out.println("基本信息新增失败!");
conn.rollback();//回滚事务
}
pstm.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ReadersDao.class.getName()).log(Level.SEVERE, null, ex);
}
return n;
}
}
运行结果及详细报错内容
数据添加成功,但是没有在数据库中显示