I want to check if my id is already exist or not:
sql2 = "SELECT stid FROM student";
stmt.executeUpdate(sql2);
rs = stmt.executeQuery(sql2);
while(rs.next()){
id = rs.getString("stid");
if(tf_insert1.equals(id)){
JOptionPane.showMessageDialog(null, "ID is already exists");
id = tf_insert1.getText();
name = tf_insert2.getText();
address = tf_insert3.getText();
gender = tf_insert4.getText();
ip = tf_insert5.getText();
tf_insert1.setText(id);
tf_insert2.setText(name);
tf_insert3.setText(address);
tf_insert4.setText(gender);
tf_insert5.setText(ip);
Any idea to solve this thing???
Please check this. I have modified code in 2 parts.
One for checking the id exists or not
and another for insert section.
Hope it will help to solve your issue.
private void yourFunction(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"SELECT stid FROM student where stid = ?");
stmt.setLong(1, Long.parseLong(stid.getText()));
ResultSet rs=stmt.executeQuery();
bool recordAdded = false;
while(!rs.next()){
recordAdded = true;
}
if( recordAdded ){
// your code for insertion.
}else{
JOptionPane.showMessageDialog(null, "ID is already exists");
}
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
Related
I have a music database so I'll need a search function, now when entering into the search bar, I get the error : "Invalid argument in JDBC call: parameter index out of range: 1"
public static Song getSongByName(String name)
{
String sql =
"SELECT songID FROM Song "+
"WHERE name = '?'; ";
Connection conn = Connections.getConnection();
Song erg = null;
try
{
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
ResultSet rs = pstmt.executeQuery();
rs.next();
int id = rs.getInt (1);
name = rs.getString (2);
erg = new SongImpl(id,name);
rs.close();
pstmt.close();
}
catch(SQLException exc)
{
System.err.println("Fehler: in SQL-Aufruf");
System.err.println("["+sql+"]");
exc.printStackTrace();
System.exit(6);
}
Connections.putConnection(conn);
return erg;
}
It seems like you are selecting just one column instead of two.
The correct SQL query would be:
SELECT songID, songName FROM Song WHERE name = '?';
Try this:
public static Song getSongByName(String name)
{
String sql =
"SELECT songID, songName FROM Song "+
"WHERE name = ?";
Connection conn = Connections.getConnection();
Song erg = null;
try
{
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
ResultSet rs = pstmt.executeQuery();
rs.next();
int id = rs.getInt(1);
String name = rs.getString(2);
erg = new SongImpl(id, name);
rs.close();
pstmt.close();
}
catch(SQLException exc)
{
System.err.println("Fehler: in SQL-Aufruf");
System.err.println("["+sql+"]");
exc.printStackTrace();
System.exit(6);
}
Connections.putConnection(conn);
return erg;
}
Let me know if that helped :)
Look onto examples https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Try to remove single quotes:
String sql =
"SELECT songID FROM Song "+
"WHERE name = ?; ";
You should use string parameters without quotes because your statement interpreted as a SQL query without parameters.
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) {
}
}
}
I have this piece of code where I prompt the user to enter the depID to edit a department and then through the IF statement I have done it displays either saved or department doesn't exists. Now my problem is that it's going directly to the else statement. When I used debugging I noticed that the RS (ResultSet) is only comaring the users input to the first row of the table which is AOL.
try{
String value1 = txt_depID.getText();
String value2 = txt_depName.getText();
String sql = "Update tblDepartment set depID = '"+value1+"' , depName = '"+value2+"' where depID = '"+value1+"'";
String sql1 = "Select depID, depName from tblDepartment";
Class.forName(driver);
conn = DriverManager.getConnection(url);
ps = conn.prepareStatement(sql1);
rs = ps.executeQuery();
ps = conn.prepareStatement(sql);
ps.execute();
if(rs.next()){
String depi = rs.getString("depID"); //Issue: only reading first row
if(depi.equals(value1)){
JOptionPane.showMessageDialog(null, "Entry Saved");
}
else{
JOptionPane.showMessageDialog(null, "Department doesn't exist");
}
}
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
You can do this in one cycle. You should be using executeUpdate.
String sql = "Delete from tblEmployee where staffNo=?";
String sql1 = "Select * from tblEmployee";
Class.forName(driver);
conn = DriverManager.getConnection(url);
ps = conn.prepareStatement(sql1);
int result = ps.executeUpdate();
if (result > 0) {
// success
}
Here's what executeUpdate results:
Returns: either (1) the row count for SQL Data Manipulation Language
(DML) statements or (2) 0 for SQL statements that return nothing
I'm trying to find out if data from my DB matches user input. I have tried this code, but its not doing what I need it to do. I would like it to display a message saying whether or not they match.
try {
String find = BC.getText(); //Get text from Textfield
String sql = "select * from Inventory where Barcode=?";
st = con.prepareStatement(sql);
rs = st.executeQuery();
while (rs.next()) {
if("Barcode".equals(find))
{
JOptionPane.showMessageDialog(null,"Matching");
}
else JOptionPane.showMessageDialog(null,"not matching");
}
} catch (Exception ex) {
}
Put the parameter that you want to search.See this;
String find = BC.getText(); //Get text from Textfield
String sql = "select * from Inventory where Barcode=?";
st = con.prepareStatement(sql);
st.setString(1, "12345678");//Set Barcode value.
rs = st.executeQuery();
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.