<html>
<body>
<pre>
geting a error when click on the update button as : "com.microsoft.sqlserver.jdbc.SQLServerException: Violation of PRIMARY KEY constraint 'PK_customer'. Cannot insert duplication key in object 'dbo.Customer'. The duplication key value is ()."
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://localhost:1433;databaseName=77OOP062;user=sa;password=hnd";
Connection conn= DriverManager.getConnection(url);
String value1=jTextFieldCustomerName.getText();
String value2=jTextFieldHomeAddress.getText();
String value3=jTextFieldNIC.getText();
String value4=jTextFieldEmailAddress.getText();
String value5=jTextFieldContactNo.getText();
String value6=jLabel7.getText();
pst=conn.prepareStatement("update Customer set CustomerName=?,HomeAddress=?,NIC=?,EmailAddress=?,ContactNo=?,InvoiceNo=?");
pst.setString(1,value1);
pst.setString(2,value2);
pst.setString(3,value3);
pst.setString(4,value4);
pst.setString(5,value5);
pst.setString(6,value6);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Güncellendi");
}catch(Exception e){;
JOptionPane.showMessageDialog(null, e);
}
distable();
}
</pre>
</body>
</html>
geting a error when click on the update button as : "com.microsoft.sqlserver.jdbc.SQLServerException: Violation of PRIMARY KEY constraint 'PK_customer'. Cannot insert duplication key in object 'dbo.Customer'. The duplication key value is ()."
since your update statement doesn't include a where clause, your statement tries to update all rows in the table and since you've put primary key column NIC in the update statement, it also get's overwritten but after the first write rdbms realizes your putting the same value in NIC column(which isn't allowed as pk must be unique) and thus gives you the error.
use a where clause to filter rows u want to update and don't update the pk.
Related
I am trying to insert data into a CUSTOMER table.
private void c_enterActionPerformed(java.awt.event.ActionEvent evt) {
String insertSQL = "insert into CUSTOMER(CUST_ID, CUST_NIC, CUST_FNAME,CUST_LNAME, CUST_EMAIL, CUST_ADDRESS, CUST_PHONE, CUST_IMG) values(?,?,?,?,?,?,?,?)";
try{
ps = con.prepareStatement(insertSQL);
ps.setString(1,c_id_text.getText());
ps.setString(2,c_nic_text.getText());
ps.setString(3,c_fname_text.getText());
ps.setString(4,c_lname_text.getText());
ps.setString(5,c_email_text.getText());
ps.setString(6,c_address_text.getText());
ps.setString(7,c_phone_text.getText());
ps.setString(8,img_path_txt.getText());
ps.execute();
JOptionPane.showMessageDialog(null, "New Customer Inserted\nCongratulations!");
c_id_text.setText("");
c_nic_text.setText("");
c_fname_text.setText("");
c_lname_text.setText("");
c_email_text.setText("");
c_address_text.setText("");
c_phone_text.setText("");
img_path_txt.setText("");
updateTable();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Insertion error: "+e);
}
}
The table was created using:
CREATE TABLE CUSTOMER(
CUST_ID INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
CUST_NIC VARCHAR(14),
CUST_FNAME VARCHAR(20),
CUST_LNAME VARCHAR(25),
CUST_EMAIL VARCHAR(45),
CUST_ADDRESS VARCHAR(60),
CUST_PHONE INTEGER,
CUST_IMG VARCHAR(100));
SELECT * FROM AKASH.CUSTOMER FETCH FIRST 100 ROWS ONLY;
I have disabled the CUST_ID text as shown. It's telling me "Attempt to modify an identity column 'CUST_ID'.
Now, for claritfication: I know what is happening. But I don't know how to fix it.
I tried to remove ps.setString(1,c_id_text.getText()); , that didn't work.
I also tried to remove CUST_ID from String insertSQL... , but to no avail.
If I try to input data from the SQL using "Insert row" button, it works and the CUST_ID column displays ""
Found my mistake. Solved after commenting out
ps.setString(1,c_id_text.getText());
and c_id_text.setText("");
as well as removing CUST_ID form the insertSQL line of code.
I'm working at some school project and my job here is to make a delete button for that list view in Java FX, but the problem is that when i want to proceed that it shows me this error. I tried some solutions, but none of them worked.
so here's the code
#FXML
private void removeStudentOnClick(ActionEvent event) throws IOException, SQLException{
ModelEditStudent student=(ModelEditStudent)tables.getSelectionModel().getSelectedItem();
String sql="DELETE FROM student WHERE nr_indeksu=?";
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Usuwanie studenta");
alert.setHeaderText(null);
alert.setContentText("Czy na pewno chcesz usunąc tego studenta z listy?");
Optional <ButtonType> action = alert.showAndWait();
if(action.get() == ButtonType.OK){
tables.getItems().removeAll(tables.getSelectionModel().getSelectedItem());
try{
try (Connection myConn = ConnectionManager.getConnection()) {
try (PreparedStatement st = myConn.prepareStatement(sql)) {
st.setString(1, student.getNr_indeksu());
st.executeUpdate();
}
myConn.close();
}
}catch (SQLException e){
System.out.println(e);
}
}
and there's the error:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot delete or update a parent row: a foreign key constraint fails
(`wu`.`oceny`, CONSTRAINT `oceny_ibfk_3` FOREIGN KEY (`nr_indeksu`)
REFERENCES `student` (`nr_indeksu`))
All the point of this operation is about selecting the row and removing from the database after pressing a button. By now it works only for the listview, but it doesn't remove records from the database.
Anyone got an idea how make it work?
I believe the problem is in your DB schema. try fixing the foreign keys dependencies.I mean the value of nr_indeksu exists in another table of your DB.
You have a table called oceny which has a column nr_indeksu that contains student ids. You have created a foreign key constraint on that table, which requires those student ids to match up with something in the student table.
If you try to delete something in the student table that's referenced by the oceny table, you will get this error, because otherwise, it would leave the database in a state where the oceny table references a student that doesn't exist.
There are a number of solutions to this. You will need to think about what should actually happen in this case - what do you want to have happen to the oceny rows when you delete a matching student.
One option would be for you to change the foreign key to make it do a "cascade delete" - that is, the oceny automatically gets deleted in the same transaction as the student. There's some information here on how to do that.
I need a bit of assistance in getting a connection between my two tables
These are the tables where "idPatient is the foreign key"
I fill the table "tanden" like this
public void addTandenToDatabase(int id, int fdi, String voorstelling, String toestand) {
String insertSql = "insert into tanden(id, fdi, voorstelling, toestand) values (:idVal, :fdiVal, :voorstellingVal, :toestandVal)";
try (Connection con = sql2o.open()) {
con.setRollbackOnException(false);
con.createQuery(insertSql)
.addParameter("idVal", id)
.addParameter("fdiVal", fdi)
.addParameter("voorstellingVal", voorstelling)
.addParameter("toestandVal", toestand)
.executeUpdate();
}
}
Everything is added nicely but the idPatient stays null
You should include idPatient in your insert if you want to set value to it. 'foreign key' doesnot mean that it will be set value automically.
You have to insert idPatient column value into tanden table by taking from patienten table.
Your id column in the tanden table should be set as primary key and autoincrement and you have to set the idPatient in your insert
insert into tanden(idPatient, fdi, voorstelling, toestand) values(:idVal,:fdiVal, :voorstellingVal, :toestandVal)";
(The idPatient you set in the child table already has to exist in the parent table
I am creating a method to load in vales from an interface to create a new record in my database.
I have tried several methods and keep getting different errors.
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '939' for key 'PRIMARY'
public boolean newStudent(String studentId, String name, String degreeScheme) throws SQLException
{
// Use SIMPLEDATASOURCE connection
Connection conn = SimpleDataSource.getConnection();
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'student_name = 'mark' degree_Scheme = 'cis'' at line 1
try {
conn.createStatement();
PreparedStatement stat = conn.prepareStatement( "UPDATE student SET studentId = ?");
stat.setString(1,studentId); // Use parameter
stat.executeUpdate(); // Execute prepared stat
return stat.executeUpdate() == 1 ;
}
finally
{
// Close the connection
conn.close();
}
}
Was there a question in there somewhere?
Duplicate entry '939' for key 'PRIMARY'
This indicates that you are either inserting a row or updating a row to have a PRIMARY KEY value that already exists in the table. (The value of the column(s) making up the PRIMARY KEY must be UNIQUE on each row; no two rows can have the same value.)
This query:
UPDATE student SET studentId = ?
Is going to attempt to set the studentId column to the same value on every row.
We're guessing that studentId is defined as the PRIMARY KEY of the student table, and that the table contains more than one row. We'd expect the execution of this statement to throw a "duplicate key" exception, like the one you are reporting.
This is my code for executing in my java program:
public static void createBooksTablesAndSetPK() {
String selectDB = "Use lib8";
String createBooksTable = "Create table IF NOT EXISTS books (ID int,Name varchar(20),ISBN varchar(10),Date date )";
String bookTablePK = "ALTER TABLE BOOKS ADD PRIMARY KEY(id)";
Statement st = null;
try (
Connection con = DriverManager.getConnection(dbUrl, "root", "2323");) {
st = con.createStatement();
st.execute(selectDB);
st.execute(createBooksTable);
st.execute(bookTablePK);
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
I cat use IF NOT EXIST for creating databasesand tables to prevent creating duplicate database and tables and corresponding errors.
But i don't know how prevent Multiple primary key error, because program may call createBooksTablesAndSetPK() multiple times.
Error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Multiple primary key defined
The column Book_id is not existing in your case. You are creating a table with ID as the column and then updating the table with a PRIMARY KEY constraint on a column that is not existing.
Create table IF NOT EXISTS books (ID int,Name varchar(20),ISBN varchar(10),Date date )
ALTER TABLE BOOKS ADD PRIMARY KEY(BOOK_id)
Try running these statements on a MySQL command prompt (or MySql Workbench) and the see the error.
You need change the alter table command like this.
ALTER TABLE BOOKS ADD BOOK_id VARCHAR( 255 ), ADD PRIMARY KEY(BOOK_id);