I am doing a project in Java Swing and using SQLite as my database.
This is the function I wrote for deleting a record from the Room table in my database.
public void Delete() {
String room_code = jTextField5.getText();
String sql = "DELETE FROM Room WHERE room_code = '" + room_code + "'";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Room Deleted Successfully");
}
else {
JOptionPane.showMessageDialog(null, "Invalid Room Code");
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
However, I am met with the following Exception: SQLException: query does not return results.
I have tried to use pst.executeUpdate() as suggested in other answers but it says "int cannot be converted into resultset".
A DELETE statement does not return a result set. You should call method executeUpdate rather than method executeQuery.
Also, you can use place holders with a PreparedStatement.
Also you should use try-with-resources
Consider the following code.
public void Delete() {
String room_code = jTextField5.getText();
String sql = "DELETE FROM Room WHERE room_code = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(room_code);
int count = ps.executeUpdate();
if (count > 0) {
JOptionPane.showMessageDialog(null, "Room Deleted Successfully");
}
else {
JOptionPane.showMessageDialog(null, "Invalid Room Code");
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
Related
I curently work on few SQL queries (MSSQL 2O14), but only "SELECT" query works with executeQuery().
I had use execute() and executeUpdate() on "INSERT INTO" and "UPDATE" queries, but whereas it looks like working, no way.
FYI, in "UPDATE_PREVIOUS_H_LOT_STATUT,
int count= p.executeUpdate(); return 1. If h_lot_number is an unknown lot number, count = 0.
So, if I use wrong data in input, my query isn't executed(Until here, I agree) but when I use the expected data, the query is executed but there is no change in my DB.
How can I find where my error is ?
UPDATE Function :
public static boolean UPDATE_PREVIOUS_H_LOT_STATUT(String h_lot_number_old) {
try {
setUpConnexion("mainDB");
String baseQuery = "UPDATE valve_assembly_h SET statut = 'Expiré' WHERE h_lot_number = '" + h_lot_number_old + "'";
//PreparedStatement p = newTransact("UPDATE valve_assembly_h SET statut = 'Expiré' WHERE h_lot_number = '" + h_lot_number_old + "'", "mainDB");
PreparedStatement toReturn = (PreparedStatement) mainCon.prepareStatement(baseQuery);
int count = toReturn.executeUpdate();
if (count > 0) {
Log.d("Sucess : ", "Previous h_lot updated.");
closeCons();
return true;
} else {
Log.e("Error : ", "No lot found with this number.");
closeCons();
return false;
}
} catch (SQLException e) {
error = e.getMessage();
Log.e("Error :", error);
closeCons();
return false;
}
}
LOAD PREVIOUS NUMBER FUNCTION (works perfectly)
public static String LOAD_PREVIOUS_H_LOT_NUMBER(String machineNumber) {
String s = "";
try {
setUpConnexion("mainDB");
ResultSet RS = executeQuery("SELECT h_lot_number FROM valve_assembly_h WHERE machine_number = '" + machineNumber + "' AND statut = 'Actif'", "mainDB");
while (RS.next()) {
s = RS.getString(1);
Log.d("Success : ", "Lot number : " + s);
}
closeResultSet(RS);
} catch (Exception e) {
error = e.getMessage();
Log.e("Error :", error);
s = error;
}
closeCons();
return s;
}
Set up connection function : (works perfectly)
public static boolean setUpConnexion(String DBNAME) {
StrictMode.ThreadPolicy policy;
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String connectURL;
try {
CONNECTION MS SQL SERVER
}
return true;
} catch (Exception e) {
System.out.println("SQL ERROR: " + e.getMessage());
e.printStackTrace();
return false;
}
}
Try to commit the transaction manually through the Connection object ,hope it helps.
I have code, where I have single quote or APOSTROPHE in my search
I have database which is having test table and in name column of value is "my'test"
When running
SELECT * from test WHERE name = 'my''test';
this works fine
If I use the same in a Java program I am not getting any error or any result
But If I give the name with only single quote then it works
SELECT * from test WHERE name = 'my'test';
Could you please help me out to understand.
Java code is
Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:#localhost:1521:orcl"
,"user","pwd");
String query = "SELECT * from "
+ "WHERE name = ? ";
prSt = con.prepareStatement(query);
String value = "my'mobile";
char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
if (content[i] == '\'')
{
result.append("\'");
result.append("\'");
}
else
{
result.append(content[i]);
}
}
prSt.setObject(1, result.toString());
int count = prSt.executeUpdate();
System.out.println("===============> "+count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
You don't have to escape anything for the parameter of a PreparedStatement
Just use:
prSt = con.prepareStatement(query);
prSt.setString("my'mobile");
Additionally: if you are using a SELECT statement to retrieve data, you need to use executeQuery() not executeUpdate()
ResultSet rs = prst.executeQuery();
while (rs.next())
{
// process the result here
}
You might want to go through the JDBC tutorial before you continue with your project: http://docs.oracle.com/javase/tutorial/jdbc/index.html
This question already has answers here:
Passing table name as parameter of prepared statement [duplicate]
(3 answers)
Closed 6 years ago.
public List<User> arrangeUsers(String option) {
String query = "";
if (option.equals("lastNameAsc")) {
query = "SELECT * FROM ? ORDER BY lastName ASC;";
} else if (option.equals("lastNameDesc")) {
query = "SELECT * FROM ? ORDER BY lastName DESC;";
} else if (option.equals("dobAsc")) {
query = "SELECT * FROM ? ORDER BY dateOfBirth ASC;";
} else if (option.equals("dobDesc")) {
query = "SELECT * FROM ? ORDER BY dateOfBirth DESC;";
}
boolean listChoice;
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(query);) {
if (searchList.size() > 0) {
stmt.setString(1, "search_results");
searchList.clear();
listChoice = true;
} else {
stmt.setString(1, "users");
users.clear();
listChoice = false;
}
ResultSet result = stmt.executeQuery();
while (result.next()) {
User user = new User();
user.setFirstName(result.getString("firstName"));
user.setLastName(result.getString("lastName"));
user.setDob(result.getDate("dateOfBirth"));
user.setPhoneNumber(result.getString("phoneNumber"));
user.setEmail(result.getString("email"));
user.setUserID(result.getInt("id"));
if (listChoice) {
searchList.add(user);
} else {
users.add(user);
}
}
} catch (SQLException sqle) {
System.err.println(sqle);
sqle.printStackTrace();
return null;
}
if (listChoice) {
return searchList;
} else {
return users;
}
}
The above method returns an error:
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 ''users' ORDER BY lastName DESC' at line 1 " error.
The method is supposed to arrange a list of users (a table) according to the order required by the client. Any suggestions what is the reason for the error message? I am ready to provide any additional details if necessary.
A table name can't be used as a parameter. It must be hardcoded. You can do something like:
public List<User> arrangeUsers(String option) {
String query = "SELECT * FROM ";
if (searchList.size() > 0) {
query += "search_results ";
searchList.clear();
listChoice = true;
} else {
query += "users ";
users.clear();
listChoice = false;
}
if (option.equals("lastNameAsc")) {
query += "ORDER BY lastName ASC;";
} else if (option.equals("lastNameDesc")) {
query += "ORDER BY lastName DESC;";
} else if (option.equals("dobAsc")) {
query += "ORDER BY dateOfBirth ASC;";
} else if (option.equals("dobDesc")) {
query += "ORDER BY dateOfBirth DESC;";
}
boolean listChoice;
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(query);) {
ResultSet result = stmt.executeQuery();
while (result.next()) {
User user = new User();
user.setFirstName(result.getString("firstName"));
user.setLastName(result.getString("lastName"));
user.setDob(result.getDate("dateOfBirth"));
user.setPhoneNumber(result.getString("phoneNumber"));
user.setEmail(result.getString("email"));
user.setUserID(result.getInt("id"));
if (listChoice) {
searchList.add(user);
} else {
users.add(user);
}
}
} catch (SQLException sqle) {
System.err.println(sqle);
sqle.printStackTrace();
return null;
}
if (listChoice) {
return searchList;
} else {
return users;
}
}
Hope it helps.
I'm using phpmy admin and I need to Display "Not Found" message in case searching element is not found in the DB.
Used code is here.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
I used this method to search empId ,if empId is not available in db I need to display a message.Please give me a solution how to detect, if empId is not available in DB.
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("Not Found");
}
Use if statement like this
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
do
{
// If there is data, then process it
}
while(rs.next());
}
else
System.out.println("Not Found");
Added parse of text to integer, assuming empId is an integer.
int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
String sql = "SELECT *" +
" FROM nonacademic" +
" WHERE empId = ?";
try (Statement s = c.prepareStatement(sql)) {
s.setInt(1, empId);
try (ResultSet rs = s.executeQuery()) {
if (! rs.next()) {
// not found
} else {
// found, call rs.getXxx(...) to get values
}
}
}
}
Just use the basic simple if & else statement. If the ResultSet is "null" or it doesn't contain any record display the Message otherwise read data & display.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
// record found do the processing
else
System.out.println("Not Found");
String e = txtempId.getText();
String sql="select *from nonacademic where empId='"+ e+"' ";
try {
boolean status=DatabaseConnection.checkValue(sql);
if (status) {
JOptionPane.showMessageDialog(null,
"This id is available");
} else {
JOptionPane.showMessageDialog(null,
"Not found");
}
} catch (Exception e) {
}
This method return check whether the search element is exist or not
public static boolean checkValue(String sql) throws Exception {
boolean b = false;
ResultSet rst = null;
Statement st = getStatement();
rst = st.executeQuery(sql);
if (rst.next()) {
b = true;
}
return b;
}
The password and username are retrieved from the database. If one row is returned, a user exists. However, the below code says that the user does not exist even if the username and password are correct.
if(con != null) {
try {
String query = "select * from users where username = '"+user.getText()+"' and password = '"+pasword.getText()+"'";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
int count = 0;
while(rs.next()) {
count = count + 1;
}
if(count == 1) {
JOptionPane.showMessageDialog(null, "user exist");
} else {
JOptionPane.showMessageDialog(null, "user doesnot exist");
}
rs.close();
ps.close();
} catch (Exception e1) {
}
}
It´s a sensible code, but you should to write the
e.printStackTrace()
in the catch block, maybe an exception it's occurs. Check the user.getText() and password.getText() content, also you can apply an user.getText().trim() for example, to delete de blank spaces. Then try this:
while(rs.next()) {
count++;
}
if(count > 0) {
JOptionPane.showMessageDialog(null, "user exist");
} else {
JOptionPane.showMessageDialog(null, "user doesnot exist");
}
Good luck!