public int Insert(Course cou) throws SQLException{
Connection con = jdbc.con();//连接数据库
//sql语句的预编译防止sql注入 ,?代表占位符
//表名和属性要与数据库表明和属性一至
String sql = "insert into course (id,name,type,grade,teacher,introduction) values(?,?,?,?,?,?)";
//创建PreparedStatement对象用来执行sql语句
PreparedStatement per = con.prepareStatement(sql);
//添加和得到各个属性的值
per.setString(1, cou.getId());
per.setString(2,cou.getName());
per.setString(3,cou.getType());
per.setDouble(4, cou.getGrade());
per.setInt(5,(int)cou.getGrade()*18);
per.setString(6, cou.getTeacher());
per.setString(7, cou.getIntroduction());
//执行sql语句,executeUpdate()获取影响的行数并返回
int rows = per.executeUpdate();
return rows;
}
数据库中一共有七个属性,第五个属性time的值是第四个grade乘以18,但是我传入的参数不包括time,我想自动更新time。请问这个代码怎么改呀,一直报错
可以将更新 time 属性的逻辑放到 Course
类中,例如在设置 grade
的时候顺便更新 time
,如下所示:
public class Course {
private String id;
private String name;
private String type;
private double grade;
private int time;
private String teacher;
private String introduction;
public void setGrade(double grade) {
this.grade = grade;
this.time = (int) (grade * 18);
}
// getters and setters
// ...
}
这样,每当设置 grade
时,time
也会被自动更新。因此在调用 Insert()
方法时,只需要将 cou
的其他属性设置好即可,time
会在 setGrade()
方法中自动更新。代码如下:
public int Insert(Course cou) throws SQLException{
Connection con = jdbc.con();//连接数据库
//sql语句的预编译防止sql注入 ,?代表占位符
//表名和属性要与数据库表名和属性一致
String sql = "insert into course (id,name,type,grade,time,teacher,introduction) values(?,?,?,?,?,?,?)";
//创建PreparedStatement对象用来执行sql语句
PreparedStatement per = con.prepareStatement(sql);
```
//添加和得到各个属性的值
报什么错?类型不一致么还是
select * from information_schema.processlist where Command != ‘Sleep’ order by Time desc;