添加数据问题
老师,您好!在给goods表添加数据成功后二次运行就会报异常导致程序运行中止,我先知道如何使得添加重复数据程序可以提示已存在并继续执行下去?另外,对数据库表中数据进行增删改查操作后,数据的id能不能重新排序而不会因为删除了中间的一条数据导致id空缺。
下面以我写的代码示例:
import java.sql.*;
/**
* 对goods表进行CRUD
*/
public class CRUDgoods {
Connection conn = DButile.getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
// 增加数据
public void create() throws SQLException {
pstmt = conn.prepareStatement("INSERT INTO goods(id, name, price, desp) VALUES(?, ?, ?, ?)");
pstmt.setInt(1, 5);
pstmt.setString(2, "耳机");
pstmt.setFloat(3, 200f);
pstmt.setString(4, "蓝牙耳机");
int ct = pstmt.executeUpdate();
System.out.println(ct==1? "添加数据成功" : "添加数据失败");
read();
}
// 删除数据
public void delete() throws SQLException {
pstmt = conn.prepareStatement("DELETE FROM goods WHERE name=?");
pstmt.setString(1, "空调");
int dt = pstmt.executeUpdate();
System.out.println(dt==1? "删除数据成功" : "删除数据失败");
read();
}
// 修改数据
public void update() throws SQLException {
pstmt = conn.prepareStatement("UPDATE goods SET price=? WHERE name=?");
pstmt.setFloat(1, 1999f);
pstmt.setString(2, "手机");
int ut = pstmt.executeUpdate();
System.out.println(ut==1? "修改数据成功" : "修改数据失败");
read();
}
// 查询数据
public void read() throws SQLException {
pstmt = conn.prepareStatement("SELECT * FROM goods");
rs = pstmt.executeQuery();
while (rs.next()) {
Integer id = rs.getInt("id");
String name = rs.getString("name");
Float price = rs.getFloat("price");
String desp = rs.getString("desp");
System.out.println(id + "-" + name + "-" + price + "-" + desp);
}
}
public static void main(String[] args) {
CRUDgoods crud = new CRUDgoods();
try {
crud.create();
System.out.println("********************");
crud.delete();
System.out.println("********************");
crud.update();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
try {
DButile.close(crud.conn);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
8
收起
正在回答 回答被采纳积分+1
1回答
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星