【发布时间】:2018-10-09 23:47:50
【问题描述】:
放轻松,正在上 CS 课的中学老师。我有一个 Java 程序,它询问用户名、身高、体重,进行一些计算并将结果提供给用户。我现在需要将这些数据存储在数据库中。在开始使用主键和外键之前,我可以获取要存储的数据。
这是我无法弄清楚的错误: 错误:java.sql.SQLIntegrityConstraintViolationException:该语句已中止,因为它会导致在“USERPROFILE”上定义的“SQL180429151131780”标识的唯一或主键约束或唯一索引中出现重复键值。
这是我的桌子:
drop table stayfitapp.userdata;
drop table stayfitapp.userprofile;
drop schema stayfitapp restrict;
create schema stayfitapp;
create table stayfitapp.userprofile
(
profileName varchar(255) not null primary key,
profileGender varchar(255) not null
);
create table stayfitapp.userdata
(
profileAge double not null,
profileWeight double not null,
profileHeight double not null,
profileWaistCircumference double not null,
profileHipCircumference double not null,
profileName varchar(255),
foreign key (profileName) references stayfitapp.userprofile(profileName)
);
这是写入表的“应用程序”部分...
public void save(){
try {
String query = "insert into stayfitapp.userprofile" + "(profileName, profileGender)" + "values" + "(?,?)";
String query2 = "insert into stayfitapp.userdata" + "(profileAge, profileWeight, profileHeight, profileWaistCircumference, profileHipCircumference)" + "values" + "(?,?,?,?,?)";
Connection myConnection = DriverManager.getConnection("jdbc:derby://localhost:1527/stayfitDB2", "username", "password");
Statement myStatement = myConnection.createStatement();
//Statement myStatement2 = myConnection.createStatement();
PreparedStatement prepared = myConnection.prepareStatement(query);
prepared.setString(1, profileName);
prepared.setString(2, profileGender);
PreparedStatement prepared2 = myConnection.prepareStatement(query2);
prepared2.setDouble(1, profileAge);
prepared2.setDouble(2, profileWeight);
prepared2.setDouble(3, profileHeight);
prepared2.setDouble(4, profileWaistCircumference);
prepared2.setDouble(5, profileHipCircumference);
int rowsAffected = prepared.executeUpdate();
int rowsAffected2 = prepared2.executeUpdate();
if(rowsAffected==0)
{
System.out.println("Warning: User data did not save!");
}
else
{
System.out.println("User info saved!");
}
}
catch(SQLException e)
{
System.out.println("Error: "+e.toString());
}
【问题讨论】:
-
表
userprofile,列:profileName varchar(255) not null primary key,- 主键意味着,该列中的值必须是唯一的,您不能在该列中有两条或多条具有相同值的记录。例如,您正在尝试插入John,但另一个John已经在表中,并且数据库会抱怨。 -
谢谢。这个想法是用户回来使用该程序并存储他们的新数据(相同的用户名)。
-
varchar(255) 用于性别代码?
-
用户输入他们的性别。