Can we use OR clause in a PreparedStatement using java?
PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
stmt.setString(1, "'MIKE' || 'ANDY'");
int i = stmt.executeUpdate();
System.out.println(i + " records deleted");
You can simply use two parameters.
PreparedStatement stmt=con.prepareStatement("delete from emp where id=? or id=?");
stmt.setString(1,"ANDY");
stmt.setString(2,"MIKE");
No. This is not raw text substitution and you can’t drop in chunks of the query and expect them to get incorporated in. Each thing substituted for a placeholder gets sanitized, encoded, and quoted as a separate value.
But you can write it with 2 placeholders:
PreparedStatement stmt=con.prepareStatement(
“delete from emp where id in (?, ?)”);
stmt.setString(1,"MIKE”);
stmt.setString(2, “ANDY”);
If you have a lot of values in the IN clause an alternative is to put those values in a table and join to it.
Related
I want to use a SELECT subquery into a INSERT query as PreparedStatement...
I am trying to fill 2 columns with custom value and the 3rd one with subquery...
query = "insert into invoiceOrders (productCode,quantity,amount) values (?,?,select price from priceTable where proCode=pCode)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(0,"productCode");
stmt.setString(1,"qty");
/*3rd column will be filled be subquery*/
n = stmt.executeUpdate();
The subquery:
select price from priceTable where proCode=pCode
must be enclosed in parentheses and make sure that it returns only 1 row.
Also what is the parameter pCode?
I think that you should replace it with ? and pass later its value with setString().
Also the setString() method's 1st argument is 1 based.
So change to this:
query = "insert into invoiceOrders (productCode,quantity,amount) values (?,?,(select price from priceTable where proCode=?))";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1,"productCode");
stmt.setString(2,"qty");
stmt.setString(3,pCode); // or stmt.setInt(3,pCode);
n = stmt.executeUpdate();
I have raw insert query like
insert into sample(id, name) values(1, 'text \\N\');
Getting SqlException while trying to insert via jdbc but the same insert query is working if I insert via mysql command prompt(console).
jdbc insert query is failing due to special characters("\N") in name field.
so how to overcome and insert the name with \N?
The cleanest approach is to not use a raw SQL query at all. If, as you've stated, you receive the name from some other process then it is presumably in a String variable (or property, or similar) so you can simply use a parameterized query to perform the insert:
// example data
int theId = 1;
String theName = "the name you received from somewhere else";
//
PreparedStatement ps = conn.prepareStatement("INSERT INTO sample (id, name) VALUES (?, ?)");
ps.setInt(1, theId);
ps.setString(2, theName);
ps.executeUpdate();
How can I update my SQL Table column with the value that is stored in a local variable.
In my program I have taken value from the HTML page using the following statement:
String idd=request.getParameter("id");
String report=request.getParameter("rprt");
So now I have to update the value of report in my database table named "ptest" and I am using the following query:
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root");
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("update ptest set result = #reprt where patient_id=
#idd");
out.println("Successfully Entered");
But the value is not being stored in the database instead NULL is being stored.
I have already seen this question and got no help.
Question
Please ignore my mistakes if any in this question as I am new to MYSQL.
You can use prepared statements in java.
setString or setInt can set different data types into your prepared statements.
The parameter 1, 2 are basically the positions of the question mark. setString(1,report) means that it would set the string report in the 1st question mark in your query.
Hope this code helps you in achieving what you want.
String query = "update ptest set result = ? where patient_id = ?";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, report);
preparedStatement.setString(2, idd);
preparedStatement.executeUpdate();
In JDBC, you use ? as placeholders for where you want to inject values into a statement.
So you should do something like this ...
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root");
PreparedStatement st= con.prepareCall("update ptest set result = ? where patient_id=
?");
///now set the params in order
st.setString(1, report);
st.setString(2, idd);
//then execute
st.executeUpdate();
Doing a string concat with the values is dangerous due to sql injection possibilities, so I typically make statement text static and final, and also if your value has a ' in it that could blow up your sql syntax etc. Also, notice the use of executeUpdate rather than query.
Hope this helps
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,"+u+","+p+",'1')");
I'm getting the error
java.sql.SQLException: Unknown column '(the U variable)' in 'field list';
I know for sure it is 100% the "" but i can't seem to find it where it goes wrong
any help is appreciated!
This is my whole method (I want to learn how to do it with a prepared statement)
public static void connectionDB(String u, String p, String f){
{
try {
String username = "/////////";
String password = "///////";
String url = "///////////////";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Database connected!");
}
}
It should be like
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");
Update:-
You can also look into prepared statements because
Prepared statements are much faster when you have to run the same statement multiple times, with different data. Thats because SQL will validate the query only once, whereas if you just use a statement it will validate the query each time.
Assuming fields are A,B,C,D;
A is int and remains are strings
String insertTableSQL = "INSERT INTO Leden"
+ "(A,B,C,D) VALUES"
+ "(?,?,?,?)";
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "Hello");
preparedStatement.setString(3, "this");
preparedStatement.setString(4, "OP");]
preparedStatement .executeUpdate();
It should be
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')'");
The issue is, that " is used in SQL for objects like columns or tables, whereas ' is used for strings. So in +u+, which seems to not exists in context of your query.
Your query itself should therefore look something like (given, that +u+ and +p+ are strings.
INSERT INTO Leden VALUES (null,'+u+','+p+','1')
If you need to have " inside your columns, it would read like
INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')
Also I would recommend to specify the columns you are inserting to so it looks similar to:
INSERT INTO "Leden" ("col1", "col2", "col3", "col4") VALUES (null,'+u+','+p+','1')
This will prevent your query from failing when extending table definition by another column.
Also using prepared statements could be a good idea here, as it helps you preventing from e.g. SQL injections.
Having issues with this the one that needs to be set is a auto increment integer so how would I Specify that
PreparedStatement stmt = conn.prepareStatement("INSERT INTO `"+OnlineUsers.table2+"` VALUES (?,?,?)");
//What I do here
stmt.setInt(2, currentonline);
stmt.setDate(3, new java.sql.Date(b.getTime()));
stmt.execute();
It's best to specify the column names explicitly:
"INSERT INTO `" + OnlineUsers.table2 + "` (col2, col3) VALUES (?,?)"
Then:
stmt.setInt(1, currentonline);
stmt.setDate(2, new java.sql.Date(b.getTime()));
This will make your code robust to the order of the columns changing in the database.
Note: If OnlineUsers.table2 comes from an untrusted source you should validate this string, otherwise you could be at risk of an SQL injection attack.