Can i concatenate my String containing data with a mysql Query? - java

I have this code portion as :
String t = (tname2.getText());
String h = (value2.getText());
PreparedStatement ps ;
if(h.length()>2)
{
ps = con.prepareStatement("DELETE FROM "+t+" where empname = "+ h);
//ps.setString(2,h);
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "Record deleted !", "Confirmation", JOptionPane.INFORMATION_MESSAGE);
}
Now, the line ps = con.prepareStatement("DELETE FROM "+t+" where empname = "+ h); isn't working . It works the other way around using "?". As like "Delete * from "+ t +" where empname =?";
and then setting the value of empname. I wanna know , if there's a way i can do things using concatenation of my empname with the query?? Can someone provide a few hints please?? `

Use PreparedStatement with a parametrized query and set the value.
This using will also prevent SQL injection.
Because concatenate values into your query make vulnerable to SQL injection.
eg.
ps = con.prepareStatement("DELETE FROM "+t+" where empname = ?");
psmt.setString(1, h);

You are missing properly opening and closing double quotes:
Try this:
ps = con.prepareStatement("DELETE FROM " + t + " where empname = '" + h + "'");

Related

Prepared Statement in Java/SQL Server not returning any results

List<Guest> guestList = new ArrayList<>();
String query = "select * from Guests where ? like ?";
System.out.println("select * from Guests where " + property + " like '%" + value + "%'");
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, property);
preparedStatement.setString(2, "'%" + value + "%'");
ResultSet resultSet = preparedStatement.executeQuery();
guestList = getGuestListFromResultSet(resultSet);
return guestList;
As you can see above, I created a Prepared Statement, which is later populated with 2 values: property and value. Running the above query should give me some results in SQL Server.
I also tried these variations for setting the second parameter(value):
preparedStatement.setString(2, "%" + value + "%");
preparedStatement.setString(2, value);
None of these seem to work. What does work is simply building the query from string concatenation:
PreparedStatement preparedStatement = connection.prepareStatement("select * from Guests where " + property + " like '" + value + "'");
However, I want to use a Prepared Statement.
You can't use a variable as a column name. Instead, you can use dynamic SQL
String query = """
DECLARE #sql nvarchar(max) = '
select *
from Guests
where ' + QUOTENAME(?) + ' like #value;
';
EXEC sp_executesql #sql,
N'#value nvarchar(100)',
#value = ?;
""";
Note the use of QUOTENAME to correctly escape the column name.
Note also the use of sp_executesql to pass the value all the way through.
I'm not sure about the JDBC driver, but ideally you should use proper named parameters, rather than ?

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()) +")"

JDBC Delete Query with multiple conditions

I have been struggling with an SQL Delete query. I want it to delete a row, Where 2 conditions are met. The error I am getting says my SQL Syntax is wrong near the end at the last ')'.
String sql = "DELETE FROM course
WHERE (username_entry = " + username +
" AND course_name = " + courseToDelete.toUpperCase() + ")";
My variables have the right values and the data in the database corresponds perfectly.
Here is an example of what your raw query might look like:
DELETE
FROM course
WHERE username_entry = tim AND course_name = chemistry;
Of course, this is not valid SQL, because you are comparing text columns against what will be perceived as other columns called tim and chemistry. You really want the above query to look like this:
DELETE
FROM course
WHERE username_entry = 'tim' AND course_name = 'chemistry';
In other words, you need to compare against properly escaped string literals. But in practice, the best thing to do is to use prepared statements, which handle the formatting automatically:
String sql = "DELETE FROM course WHERE username_entry = ? AND course_name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, courseToDelete.toUpperCase());
ps.executeUpdate();
You need to encapsulate string values into quotes
String sql = "DELETE FROM course
WHERE (username_entry = '" + username +
"' AND course_name = '" + courseToDelete.toUpperCase() + "')";
But better way is to use prepared statements as they do automatical escape
Did you try to remove the braces after the Where clause.
The query would look like below after the change:
String sql = "DELETE FROM course
WHERE username_entry = '" + username +
"' AND course_name = '" + courseToDelete.toUpperCase()+"'";
You don't have to use any open / close paranthesis for the query as such!
As suggested in the other answers, you don't really need to use the injection of variables but instead, use the PreparedStatement
String sql = "DELETE FROM course
WHERE username_entry = '" + username +
"' AND course_name = '" + courseToDelete +"'";
Hope this helps!

How to merge multiple "SELECT" statement into one?

Currently, I am using for loop, which is unacceptably slow when orgList has thousands of elements inside:
String sql = "SELECT xua.XUAID, xua.XUA01, xua.XUA02 "
+ "FROM dbo.XDSysUseArea xua "
+ "WHERE xua.XUA03=?";
conn = ds.getConnection();
ps = conn.prepareStatement(sql);
for(HotelSource org : orgList) {
ps.setString(1, org.getPrimaryKey());
rs = ps.executeQuery();
while (rs.next()) {
// do sth
}
}
What is the right way to do the SELECT?
You should use SQL IN, for example:
SELECT ... FROM ... WHERE xua.XUA03 IN (x, y, z, ...)
You can still parameterise your query, but you need to generate the correct number of ? in the statement. So some psuedocode here because I don't do Java:
String params = "?, ?, ?, ?"; //you will have to generate enough of these yourself
//This is an exercise for you!
String sql = "SELECT xua.XUAID, xua.XUA01, xua.XUA02 "
+ "FROM dbo.XDSysUseArea xua "
+ "WHERE xua.XUA03 IN (" + params + ")";
conn = ds.getConnection();
ps = conn.prepareStatement(sql);
int index = 1;
for(HotelSource org : orgList) {
ps.setString(index, org.getPrimaryKey());
// ^^^^^ use index here
index++;
}
rs = ps.executeQuery();
while (rs.next()) {
// do sth
}
Note: The downside of this is that you mention you have thousands of entries in orgList which makes it really bad practice to use this method. In fact, SQL Server will not allow you to use more than a couple of thousand parameters.
Use IN operator no need to hit the query for each value
SELECT xua.XUAID, xua.XUA01, xua.XUA02
FROM dbo.XDSysUseArea xua
WHERE xua.XUA03 in (val1,val2,val3,..) -- pass the list here
Store org.getprimarkey() in a arraylist List<Integer> past it to where clause using in operator
SELECT xua.XUAID, xua.XUA01, xua.XUA02 "
+ "FROM dbo.XDSysUseArea xua "
+ "WHERE xua.XUA03 IN (mylist);
NOTE: replace [ ] in list using replaceall method.
You can use operator IN for this purpose. Example,
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

SQL update statement in Java

I am trying to update a field in my table using Netbeans and I have two conditions. The update statement is as follows:
String sql1 = "update tbl_log set Logout_Time =? where Firstname = ? and Check = ?";
try{
pst = conn.prepareStatement(sql1);
pst.setString(1, time);
pst.setString(2, username);
pst.setString(3, "IN");
pst.execute();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
but I am getting the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQL SyntaxErrorException: 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 'Check = 'IN' at line 1
How can I solve it?
"Check" is a reserved word, so you need to put it in backticks
Change it to:
String sql1 = "update tbl_log set Logout_Time =? where Firstname = ? and `Check` = ?";
For a list of reserved words, see here: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Try using
pst.executeUpdate();
and also
is pst a PreparedStatement?
if not change it to that...
st.executeUpdate("update reservation set busname='" +
jTextField10.getText() + "',busno='" +
jTextField9.getText() + "',cusname='" +
jTextField8.getText() + "',noofpass='" +
jTextField7.getText() + "',amount='" +
jTextField6.getText() +"' where cusname='" +
jTextField8.getText() + "' ");

Categories

Resources