how to check duplicate values go to database - java

this is my code insert into db so i want to check duplicate value how to find an show this message "All ready exist this item code or item name"
try {
String sql = "insert into itemreg(ItemID,ItemName) values(?,?)";
pst = con.prepareStatement(sql);
pst.setString(1, icode.getText());
pst.setString(2, iname.getText());
JOptionPane.showMessageDialog(null, "Item saved");
pst.execute();
tableupdate();
clear();
} catch (Exception e) {
System.out.println(e);
}

When ItemID is defined as primary key you will get an SQLException when you try to insert a row with the same id.

Related

java.sql.SQLException: Illegal operation on empty result set with no empty row

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Connection connection;
PreparedStatement ps;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "pokemon12");
ps = connection.prepareStatement("SELECT * FROM users WHERE UserName = ? AND Password = ?");
ps.setString(1, jTextField1.getText());
ps.setString(2, String.valueOf(jPasswordField1.getPassword()));
ResultSet rs = ps.executeQuery();
if(rs.next()){
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
setVisible(false);
NewApplication1 mf = new NewApplication1(rs.getString(1),rs.getString(2));
mf.setVisible(true);
}else{
JOptionPane.showMessageDialog(this, "Username Or Password Are Invalid");
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
} catch (SQLException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
i dont know why i keep getting java.sql.SQLException: Illegal operation on empty result set even tho my sql table isnt empty and the row im trying to get also isnt empty, it happens when i try to select the last and second to last row in the table, excuse my lack of knowledge im very new to sql.

Java updating mysql row if id already exists

I have a simple form with 5 fields. (txtID, txtFirstName, txtLastName, txtCheque, txtSavings). All I want to do is inserting these fields into my database table "accounts". Before that step I want to check if the ID from my txtID field already exists in my database. If yes then I want to update the database row with the content from the fields. And if not I want to create a new row with the content. So far the check if the ID exists in my DB works but if click on my btn I get the following error message: I dont relly know what I'm doing wrong.
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error
in your SQL syntax; check the manual that corresponds to your MariaDB
server version for the right syntax to use near '(LastName,
FirstName,Cheque,Savings) VALUES('Tester','Markus','450.00','50.00" at
line 1
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
String id = txtID.getText();
String checkid ="SELECT * FROM accounts where ID=?";
pst=conn.prepareStatement(checkid);
pst.setString(1, id);
rs = pst.executeQuery();
boolean recordAdded = false;
while(!rs.next()){
recordAdded = true;
}
if(recordAdded){
// the statement for inserting goes here.
}else{
String sql ="UPDATE accounts SET " + "(LastName,FirstName,Cheque,Savings) VALUES" + "(?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1,txtLastName.getText());
pst.setString(2,txtFirstName.getText());
pst.setString(3,txtCheque.getText());
pst.setString(4,txtSavings.getText());
pst.executeUpdate();
getAllAccounts();
JOptionPane.showMessageDialog(null, "Customer Updated");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
rs.close();
pst.close();
getAllAccounts();
}
catch(Exception e) {
}
}
}
do you let me to make some changes in your code?
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "UPDATE accounts SET LastName = ?, FirstName = ?, Cheque = ?, Savings = ? where id = ?";
pst=conn.prepareStatement(sql);
pst.setString(1,txtLastName.getText());
pst.setString(2,txtFirstName.getText());
pst.setString(3,txtCheque.getText());
pst.setString(4,txtSavings.getText());
pst.setString(5,txtID.getText());
int updatedRowCount = pst.executeUpdate();
// no record with id = txtID
if(updatedRowCount == 0) {
pst.close();
sql = "insert into accounts (ID,LastName,FirstName,Cheque,Savings) values (?,?,?,?,?,?) ";
pst = conn.prepareStatement(sql);
pst.setString(1,txtID.getText());
pst.setString(2,txtLastName.getText());
pst.setString(3,txtFirstName.getText());
pst.setString(4,txtCheque.getText());
pst.setString(5,txtSavings.getText());
pst.executeUpdate();
}
getAllAccounts();
JOptionPane.showMessageDialog(null, updatedRowCount > 0 ? "Customer Updated" : "Customer Inserted");
}
catch(Exception e){
getAllAccounts();
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
pst.close();
}
catch(Exception e) {
}
}
}

How to delete searched row from jtable and sql database based on searched value

I've created a sql database with a table called users. It holds the user_id, user_name and email. I've created a form that allows the user to search for any record and displays the filtered record on a JTable.
I want to delete the row the search result filters based on the searched value meaning the user can search either the user_id, user_name or email.
users {user_id, user_name, email}
This is what I have
private void deleteSelectedRows(){
try {
String sql = "DELETE from user where ? = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, searchTxt.getText());
pst.setString(2, searchTxt.getText());
((DefaultTableModel)userTable.getModel()).removeRow(userTable.getSelectedRow());
pst.execute();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
searchTxt is the text field.
This code deletes all the rows in my table.
If I change it to DELETE from user where user_id = ?, it only deletes the row when it is searched by user_id.
users {user_id, user_name, email}
private void deleteSelectedRows(){
try {
String sql = "DELETE from user where ? = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, searchTxt.getText());
pst.setString(2, searchTxt.getText());
((DefaultTableModel) userTable.getModel()).removeRow(userTable.getSelectedRow());
pst.execute();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
With that code you're always producing a complete deletion of the table because you always obtain a TRUE in your WHERE clause
If searchTxt.getText() is "hello", the prepared statement will be
DELETE from user where hello = hello
Which is equivalent to
DELETE from user where true
Or
DELETE from user
You just have to differentiate between searchTxt and columnName
private void deleteSelectedRows(){
try {
String sql = "DELETE from user where ? = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, columnName);
pst.setString(2, searchTxt.getText());
((DefaultTableModel) userTable.getModel()).removeRow(userTable.getSelectedRow());
pst.execute();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}

Error with Oracle 10g auto-incremented sequence

I created a sequence in Oracle 10g because I have to increase case_number field auto_incremently. But I'm getting an error.
private void button_saveandsubmitActionPerformed(java.awt.event.ActionEvent evt) {
con = JavaConnectDB.ConnectDB();
try{
String sql="insert into FIR_form values(case_number_sequence,?,?,?,?,?,?,?,?,?,?,?)";
pst = (OraclePreparedStatement) con.prepareStatement(sql);
pst.setString(1,text_date.getText());
pst.setString(2,text_district.getText());
pst.setString(3,text_subject.getText());
pst.setString(4,text_description.getText());
pst.setString(5,text_cfullname.getText());
pst.setString(6,text_fhname.getText());
pst.setString(7,text_caddress.getText());
pst.setString(8,text_contact.getText());
pst.setString(9,text_suspectfullname.getText());
pst.setString(10,text_suspectaddress.getText());
pst.setString(11,text_suspectdescription.getText());
rs = (OracleResultSet) pst.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "the FIR has been added successfully!!!");
con.close();
this.dispose();
}
else{
JOptionPane.showMessageDialog(null, "enter all fields appropriately first!!!");
}
con.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An error occured. try again later !!!");
}
}
The field in the table will not auto-populate because you have defined a sequence. You must either reference the sequence.nextval in your insert statement to insert the value, or add a trigger to the table to populate the column from the sequence.
See this post for an example:

check if the record exists in database

I need to check the box no if exist in the database under the remittance id that I enter if the box no exists then i need to show the message that the box no already exists but if it doesn't the it should insert new box i have written some code but its showing error
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(1, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
while(rs.next()){
rs.equals().txtboxno.getText());
}
JOptionPane.showMessageDialog(rootPane, "hello!S");
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
Try this code
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(2, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
bool recordAdded = false;
while(!rs.next()){
/// Do your insertion of new records
recordAdded = true;
}
if( recordAdded ){
JOptionPane.showMessageDialog(rootPane, "Record added");
}else{
JOptionPane.showMessageDialog(rootPane, "Record already exists");
}
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
or you could use a count:
String query = "select count(*)
from dbo.soil_det where rm_id = ? and box_no = ?";
then after executing the query you get the count with
rs.getInt(1)
using that you can decide which info to show to the user
very First You have to get count using sql if count is greater than zero then do not insert records and show message like already exists and in else part insert record. see following example
private boolean findCount(int rm_id,String box_no)
{
int count=0;
//write query here
count = assign query result;
//check count
if(count>0)
{
return false;//records exists
}else{
return true;//records do not exists
}
}
public void insertData()
{
if(findCount(1,"1")){//pass values
//Write down your insert logic
}else{
JOptionPane.showMessageDialog(rootPane, "Records Already Exists");
}
}
Note: Friend in Your Example you have not written the insert logic. only select was there
First you could add -- on the db table -- a unique constrain on the columns (rm_id, box_no), this is anyway a good thing to do.
Then you could simply try to insert the box and catch the exception and check if it is a violation of the unique constraint.
Another option (still keeping the unique constraint) would be to make a more complicated SQL insert statement that inserts only if not existing, you may google "sql insert if not exist" to find some examples...
You need to get the appropriate record from the ResultSet e.g.
boolean found = rs.getString(1).equals().txtboxno.getText());
At the moment you're simply comparing the ResultSet object itself to a string, and that won't work. The above pulls the first record from the ResultSet and performs the comparison on that (note: your datatype may be different and you may need rs.getInt(1) etc.)
Perhaps its sufficient in your case just to check if you have a ResultSet result (via rs.next())
simplified version
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(2, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
if(!rs.next()){
JOptionPane.showMessageDialog(rootPane, "Record added");
}else{
JOptionPane.showMessageDialog(rootPane, "Record already exists");
}
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
rs.next() followed by if condition returns true if the record exists in a table. if not, return false.

Categories

Resources