how to check if an entry exists in java sqlite column - java

please i am trying to check if an entry exists in an sqlite database column.
and i am using java. here is what my code looks like
String name =JTextField.getText();
String sql0 = "select * from Objects where Description like " + name;
pStmt = conn.prepareStatement(sql0);
rs = pStmt.executeQuery();
if (rs.next()) {//if there is such entry...
System.out.println("there is an entry");
} else {//no such entry add the asset normally...
System.out.println("there is no such entry");
}
the code is just a test code for testing my sqlite query...
name is the the entry to search for in the Description Column. whenever i run this i get an error saying no such column as the value i have stored as name. please i really need help on this thanks.

I am not really familiar with sql in java but propably you need to use quotes to escape the string
Change
String sql0 = "select * from Objects where Description like " + name;
To
String sql0 = "select * from Objects where Description like '" + name + "'";
Another way is to use prepared staments

Related

Error when updating MySQL database using UPDATE - SET - WHERE method in Eclipse

I am making a program using Eclipse that allows the user to update the volume of chemicals everytime they’re restocked/used, which requires them to enter the ID of the chemical and the amount they would like to add/subtract. A query is then performed to search for the chemical's ID in the database, and its volume is updated accordingly.
However, I’m having difficulties getting the volume to update. I tried adapting MySQL’s UPDATE statement from this website to SET volume = volume + amount added, WHERE chemical ID = ID entered by the user; however, there appears to be some syntax errors in my code, more specifically at the UPDATE - SET - WHERE line:
public void IDEnter() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8889/StockControlSystem","root","root");
Statement stmt = con.createStatement();
String sql = "Select * from Chemicals where `Chemical ID` ='" + txtChemical_ID.getText()+"'";
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
stmt.executeUpdate("UPDATE Chemicals" + "SET `Volume` = rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText()) WHERE `Chemical ID` in (txtChemical_ID.getText())");
}
else {
JOptionPane.showMessageDialog(null, "Invalid chemical ID");
txtChemical_ID.setText(null);
}
} catch(Exception exc) {
exc.printStackTrace();
}
}
Since I'm still new to MySQL, can someone help me correct this? Thank you so much for your help!
Your whole query is badly formatted. Change your code to this:
stmt.executeUpdate("UPDATE Chemicals SET Volume = " +
rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText())
+ " WHERE Chemical_ID in (" + txtChemical_ID.getText() + ")");
You cannot use ' single quotes when defining Column names in queries. Single quotes are used for string values!
Still, this would not be the best way to do this. use PreparedStatement!
This way:
String updateString = "UPDATE Chemicals SET Volume = ? WHERE Chemical_ID in (?)"; // Creation of the prepared statement, the ? are used as placeholders for the values
PreparedStatement preparedStatement = con.prepareStatement(updateString);
preparedStatement.setInt(1, rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText())); // Setting the first value
preparedStatement.setString(2, txtChemical_ID.getText()); // Setting the second. I am supposing that this txtChemical_ID textField has values seperated by commas, else this will not work!
preparedStatement.executeUpdate();
If you need to read more for PreparedStatement there are a lot of great resources out there. They also protect against SQL injections.
I think your problem might be with the "rs.getInt(Volume)"
Yours:
"UPDATE Chemicals" + "SET `Volume` = rs.getInt(Volume)
+ Integer.parseInt(AmountAdded.getText())
WHERE `Chemical ID` in (txtChemical_ID.getText())"
Can you try this:
"UPDATE Chemicals" + "SET `Volume` = " +
Integer.parseInt(AmountAdded.getText()) + "
WHERE `Chemical ID` in (" + (txtChemical_ID.getText()) +")"

Display duplicate entries in SQL table using Java

I am currently trying to access the primary key by searching for a duplicate field in a database in java using sql statements. My database contains a primary key for the book ids and contains multiple copies of the same book. Those books have the same ISBN but different book ids. Is it possible to extract those unique ids using an SQL select statement? Whenever I run the following select statement, I can only obtain data on one of the copies:
String queryString =
"select bid, title, author, checked from book where isbn = " + ID;
ResultSet resultSet = stmt.executeQuery(queryString);
if (resultSet.next()){
bid = resultSet.getString(1);
title = resultSet.getString(2);
author = resultSet.getString(3);
checked = resultSet.getString(4);
}
resultSet.close();
If I run the same statement in my SQL workbench, all of the data is extracted. How can I extract the unique keys in java?
rset2.next() moves the cursor to the next row. Since you don't seem to have any loop iterating through the resultset, it isn't going beyond the first row.
You have used if condition that allows you to get only the first record fetched from query.
Rather use :
while(rs.next()) {
// TO DO
}
Change the if(resultSet.next()) for while(resultSet.next()) :
String queryString =
"select bid, title, author, checked from book where isbn = " + ID;
ResultSet resultSet = stmt.executeQuery(queryString);
// "while" instead of "if"
while (resultSet.next()){
bid = resultSet.getString(1);
// etc
// do something
}
resultSet.close();
"if" only get the first element, "while" get all the element
See the answer of this question: Similar Question

SQLITE FILTER QUERY SEARCH

I'm creating a program to put on my resume seeing as I am a college student with no work experience yet. For this particular part of the program I want to allow the user to search the sqlite database for an employee by either id number, first name or last name. It is working properly, however, it will only show the employee with the name that is spelled exactly and caps sensitive. I want it so that the user can type in a single letter or more and it will show everything in the database that contains that letter or couple letters and so on.
This is what I have:
try {
String field = (String)fieldCombo.getSelectedItem();//gets jcombobox selection
//jcombobox fields are slightly different than the column names in sql table so i did this
if(field.equals("First Name")) {
newField = "firstName";
}
else if(field.equals("Last Name")) {
newField = "lastName";
}
else if(field.equals("ID Num")) {
newField = "idNum";
}
String sql = "select idNum as 'ID Number', firstName as 'First Name', lastName as 'Last Name' from tableEMPLOYEE where " + newField + " = ?";
pst = connect.prepareStatement(sql);
pst.setString(1, searchField.getText());
rs = pst.executeQuery();
empTable.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
as Tim mentioned in comment section. SQL LIKE is what you might need.
But it will not be fast if the database is big and the user types fast, it wont feel responsive enough.
For making a query in SQLITE case insensitive you can use:
SELECT * FROM ... WHERE name = 'enterName' COLLATE NOCASE

Trying to find if an item exists in database table, if it doesn' t exist. add it

I am trying to develop a program where you want to add a new book ( title, author, date,...)
but i do not want to add the author multiple times..
i want the program to check if the author already exists in the table, if not it will add him... here is my code :
public void insert_bk(String m, String a, String b, String c, String d, String e) {
String sql="Select * from author where Full_Name='"+b+"'";
System.out.println(sql);
try {
opencn();
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while (rs.next()) {
String id=rs.getString("Author_ID");
System.out.println(id);
st.executeUpdate("INSERT into book (`Book_ID`,`Title`,`Author_ID`,`Date_of_release`,`Theme`,`Edition`)"+ "VALUES ('" + m+ "','" + a+ "','" + id+ "', '" + d+ "', '" + e+ "', '" + c+ "')");
}
}
catch(SQLException exp) {
System.out.println(exp.getMessage());
}
}
In this code it just checks if the Author exists and adds the book... how can i make the condition that if the author does not exist it will add him along with the book?
Any ideas?
Thank you in advance :)
Instead of using a while-loop you should put rs.next() into an if-statement. If the call returns false no author is present and it has to be inserted.
you can do this stored procedure
declare #i int
Select #i=count(*) from author where Full_Name=#FullName
IF(#i < 1)
BEGIN
// INSERT
END
This might help
String query = "Select * from author where Full_Name='"+b+"'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader rdr;
con.Open();
cmd.ExecuteNonQuery();
rdr = cmd.ExecuteReader();
if (rdr.Read()) { // if you have an author
//do your updation code here
}
else {
//if rdr.Read() gives 0 which will be the case when our
//author wont exist past the code for adding an author here
}
You can make a conditional insert by adding the keyword IGNORE into the statement. Depending on which SQL database you are using the answer is slightly different. I'll demonstrate here the two ways for MySQL and sqlite, but of course there are more.
For MySQL
INSERT IGNORE INTO authors VALUES(?,?...,?)
For SQLite
INSERT OR IGNORE INTO authors VALUES(?,?,...,?);

SQL queries through Java, "Illegal operation on empty result set"

I'm making a db call as follows:
String sqlAlert = "SELECT * FROM demotable where demo_no ='"
+rsDemo.getString("demo_no") + "'";
ResultSet rsAlert = db.GetSQL(sqlAlert);
if (rsAlert.next()) {
String newAlert = rsAlert.getString("cust3")+"1";
String newAlertSql = "UPDATE demotable SET cust3 = '" + newAlert + "' where demo_no='" + rsDemo.getString("demo_no") + "'";
System.out.println("Update alert msg: " + newAlertSql);
db.RunSQL(newAlertSql);
} else {
System.out.println("empty result. Demo_no = "+rsDemo.getString("demo_no"));
String sqlAlertinsert = "INSERT INTO demotable VALUES('" + rsDemo.getString("demo_no") + "','','','','','<unotes></unotes>')";
db.RunSQL(sqlAlertinsert);
System.out.println("insert demo done");
String sqlAlert2 = "SELECT * FROM demotable where demo_no ='"rsDemo.getString("demo_no") + "'";
ResultSet rsAlert2 = db.GetSQL(sqlAlert2);
if (rsAlert2.next()) {
String newAlert = rsAlert2.getString("cust3")+"1";
String newAlertSql = "UPDATE demotable SET cust3 = '" + newAlert+ "' where demo_no='" + rsDemo.getString("demo_no") + "'";
System.out.println("Update alert msg: " + newAlertSql);
db.RunSQL(newAlertSql);
}
rsAlert2.close();
}
rsAlert.close();
rs.close();
I am trying to insert rows into demographiccust if rsAlert returns an empty set and then access values from it. But my code returns this exception "Illegal operation on empty result set" around "if (rsAlert2.next()) { ". Why does it return an empty set even after inserting values into the table? Please help. Thank you.
It may be because of the open cursor. You must close your first Statement, prior trying the second. ResultSet is a connected thing, when you close the Statement it get closed too. I can't see the implementation of your db.RunSQL() and db.GetSQL() methods.
However, I am having the suggestion on how you should do it, in the first place. Here you go,
Update it without querying the database
Check how many rows updated. If none, then step 3, otherwise completed
Insert the record with the correct values in the first place. No need to update it after inserting.
Tips:
Try using PreparedStatement, instead
Try to stick with Java Naming Convention
Try using meaningful names, i.e. for example your method db.GetSQL() is not returning an SQL, but contrarily asking one, and in fact returning a ResultSet.
Never return a ResultSet. This may lead to bloated code and a lot of open cursors. Don't make the user of your method to close it. Close it yourself in your method where you are performing any database query, and return the result as a bean or a list of beans.
It's just a guess, but because you are interpolating rsDemo.getString("demo_no") directly into the SQL, you may be passing an SQL statement that isn't what you want. Try using the parameter binding api.

Categories

Resources