I am writing code in Java and I want to take every time I run this code the next line from a MySQL table.The second time I run this code is this.
String timh1 = "1";
String timh2 = "2";
PreparedStatement st = null;
String sqlGrammes = "SELECT SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE LIMIT ?,? ";
try {
st = connection.prepareStatement(sqlGrammes);
st.setString(1, timh1);
st.setString(2, timh2);
But it shows me this 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 ''1','2'' at line 1
limit accepts integer parameters, so you should use ints, not Strings:
int timh1 = 1;
int timh2 = 2;
PreparedStatement st = null;
String sqlGrammes = "SELECT SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE LIMIT ?,? ";
try {
st = connection.prepareStatement(sqlGrammes);
st.setInt(1, timh1); // notice the setInt
st.setInt(2, timh2); // here too
I was able to do it without prepared statement
int i = 0;
int j = 1;
sql = "Select SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE limit "+i+ ","+j;
got first row as output.
Related
I need to write an update function where its content is different based on what parameters are passed, e.g. if I have updateBook(int id, String title, String author, int pages), I have to do something like:
String sql;
if((!title.equals("null"))&&(!author.equals("null"))&&(pages>0)))
sql = "UPDATE book SET title='"+title+"', author='"+author+"', pages="+pages;
else if(((!title.equals("null"))&&(!author.equals("null")))
sql = "UPDATE book SET title='"+title+"', author='"+author+"'";
else if(((!title.equals("null"))&&(pages>0)))
sql = "UPDATE book SET title='"+title+"', pages="+pages;
... //and so on
sql = sql + " WHERE bookid="+id+";";
The more fields I have in my table, the more checks I have to do, which is uncomfortable, and requires me to write a lot of code.
Also, doing something like:
sql = "UPDATE book SET ";
if(!title.equals("null"))
sql = sql +"title='"+title+"',";
if(!author.equals("null"))
sql = sql+"author='"+author+"',";
if(pages>0)
sql = sql+"pages="+pages";
sql = sql + ";";
can't work since the unwanted commas cause statement errors.
You can see as well that if I have something like 6, 7, 8 etc field the checks start to get too many, and I can't also do more separated update statements as if something goes wrong I would need to rollback any query that has been done in that function.
Is there any way round to get a custom update statement having to write few code?
Firstly, use a PreparedStatement.
I would do it something like the following.
List<Object> params = new ArrayList<>();
StringBuilder sql = new StringBuilder();
if(!title.equals("null")) {
sql.append("title = ?");
params.add(title);
}
if(!author.equals("null")) {
if (sql.length() > 0) {
sql.append(", ");
}
sql.append("author = ?");
params.add(author);
}
if(pages>0) {
if (sql.length() > 0) {
sql.append(", ");
}
sql.append("pages = ?");
params.add(pages);
}
if (sql.length() > 0) {
sql.insert(0, "UPDATE book SET ");
sql.append(" WHERE bookid=?");
java.sql.Connection conn = // however you obtain it
java.sql.PreparedStatement ps = conn.prepareStatement(sql.toString());
for (int i = 0; i < params.size(); i++) {
ps.setObject(i + 1, params.get(i));
}
ps.executeUpdate();
}
First I am going to try using query to retrieve the int min_stock single cell using the item description. Then put that value into a variable. I want to be able to have the variable minStock to be equal to a number. I want to use it to make operations in my program.
PreparedStatement cm = con.prepareStatement(checkMinimumStock);
ResultSet minS = cm.executeQuery("SELECT min_stock FROM items WHERE item_description = '"+item+"'");
int minStock = minS.getInt("min_stock");```
you are choose wrong way to use PrepareStatment.
you have two option to do :
1:
String sql = "SELECT min_stock FROM items WHERE item_description = ?";
PreparedStatement cm = con.prepareStatement(sql);
cm.setString(1, item);
ResultSet rs = cm.executeQuery();
2:
String sql = "SELECT min_stock FROM items WHERE item_description = '" + item + "'";
ResultSet rs = con.createStatement().executeQuery(sql);
and then
if (rs.next())
int minStock = rs.getInt("min_stock");
else
//not found any match row in DB table
Try this
String checkMinimumStock = "SELECT min_stock FROM items WHERE item_description = ? ";
PreparedStatement cm = con.prepareStatement(checkMinimumStock);
cm.setString(1,item);
ResultSet minS = cm.executeQuery();
if(minS.next()){
int minStock = rs.getInt("min_stock");
}
String checkMinimumStock = "SELECT min_stock FROM items WHERE item_description = ? ";
Forgot to add this in the beginning of the code!
I have a problem updating my table from java.
i need to check colmunID(from my table PRODUCTS) = int id(given by user input) and change thats product price in table to one given by user.
PROBLEM:
static void x(int Userid, int Userprice) {
..........................................
String sql = "UPDATE Product set Price = Userprice where ID=Userid; ";
....}
I get error that i don't have column Userprice or Userid in my database. I don't know how to write this to check int User id which is given as argument in this method and not column in my database table which does not exists.
Assuming that you have both the columns with Integer datatype in DB,
String sql = "UPDATE Product set Price="+Userprice+" where ID="+Userid;
You are not passing the actual values to it and the extra ';' is not required. Also, I suggest you to prefer prepared statements, rather than above approach
While you definitely in production code want to use prepared statements to prevent sql injection, an easy fix would be the below.
String sql = String.format("UPDATE Product set Price = %d where ID=%d ",Userprice,Userid);
String wont evaluate variables in itself.
If the table for Userid does not exist in your database, you will not be able to use this in your SQL query. There are two options for you:
1. Pass the Userid and Userprice as a variables to the SQL query
String sql = "UPDATE Product set Price = " + Userprice + "where ID=" + Userid+ "; "
Or
2. Create the table in the database and join on that
String sql = "Update A Set A.Price = b.Userprice FROM Product as A INNER JOIN User as b on A.Userid = b.ID;"
PreparedStatement ps = null;
Connection con = null;
try {
con = getConnection();
String sql = "UPDATE Product set Price = ? where ID= ? ";
ps = con.prepareStatement(sql);
ps.setString(1, Userprice);
ps.setString(2, Userid);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Product Updated");
} else {
System.out.println("Error Occured");
}
I think this is something you are looking for... The query should not contain ';' in the String for your code
I want to update the esal of emp table in my database dynamically but the query is generating error
import java.sql.*;
import java.util.*;
class JdbcEx6
{
public static void main(String args[])throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection ob = DriverManager.getConnection("jdbc:odbc:mysql1","root","root123");
Statement st = ob.createStatement();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the empid");
int eno = sc.nextInt();
System.out.println("Enter the increment");
int inc = sc.nextInt();
String myquery = "update emp set esal=esal+"+inc+"where eno="+eno;/*error here*/
int count = st.executeUpdate(myquery);
ob.close();
if(count==0)
System.out.println("Invalid employee Id provided");
else
System.out.println("Updated successfully");
}
}
/*manual that corresponds to your MySQL server version for the right syntax to use near 'eno=100' at line 1
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:3110)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:338)
at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(JdbcOdbcStatement.java:288)
at JdbcEx6.main(a7.java:18)*/
As others explain, the problem can be solved by adding a whitespace to the where:
String myquery = "update emp set esal=esal+" + inc + " where eno="+eno;
//....................................................^ here
int count = st.executeUpdate(myquery);
A better solution would be to use PreparedStatement rather than plain string concatenation. Here's an example:
//query is more readable and easier to understand
//this way is easier to spot problems in the query
//? means a parameter to use in the query
String myquery = "update emp set esal=(esal+?) where eno=?";
//the connection prepares the query
PreparedStatement pstmt = ob.prepareStatement(myquery);
//set the parameters in the PreparedStatement
pstmt.setInt(1, inc);
pstmt.setInt(2, eno);
//execute the statement, which will replace the ? by the parameters
int count = pstmt.executeUpdate();
String myquery = "update emp set esal=(esal+'"+inc+"') where eno='"+eno"';
This works
You are not including spaces correctly in your query. SQL queries in java need spaces correctly just like they do in standard SQL usage.
I need to execute a SQL PreparedStatement in Java using jdbc.
I'm facing problems with one of the parameters because it has SQL content and also Strings from a resource file.
It looks something like this:
Required SQL:
SELECT * FROM Table T WHERE T.value = 10 AND T.display IN ('Sample1', 'Sample2')
In the above query, the Sample1 and Sample2 values must be passed through a parameter to a PreparedStatement.
PreparedStatement:
SELECT * FROM Table T WHERE T.value = 10 ?
In my application code I'm setting the parameters like:
statement.setString(1, "AND T.display IN ('Sample1', 'Sample2')");
However this is not returning the appropriate results.
Is there a better way to build this particular parameter considering it has SQL content and Strings too?
EDIT:
Sample1, Sample2 etc. are strings that are retrieved from an external file at run-time and there can be different number of these strings each time. I.e. there can be only one string Sample1 or multiple strings Sample1, Sample2, Sample3, etc..
EDIT2:
Database being used is Oracle.
The ? placeholder can only be used in a position where a value is expected in the query. Having a ? in any other position (as in your question: WHERE T.value = 10 ?) is simply a syntax error.
In other words: it is not possible to parametrize part of the query itself as you are trying to do; you can only parametrize values. If you need to add a dynamic number of parameters, you will need to construct the query dynamically by adding the required number of parameters and using setString(). For example:
StringBuilder sb = new StringBuilder(
"SELECT * FROM Table T WHERE T.value = 10 AND T.display IN (?");
// Note: intentionally starting at 1, first parameter already above
// Assuming always at least 1 parameter
while (int i = 1; i < params.length; i++) {
sb.append(", ?");
}
sb.append(')');
try (
PreparedStatement pstmt = con.prepareStatement(sb.toString())
) {
for (int i = 0; i < params.length; i++) {
pstmt.setString(i + 1, params[i]);
}
try (
ResultSet rs = pstmt.executeQuery();
) {
// Use resultset
}
}
Use this as PreparedStatement
"SELECT * FROM Table T WHERE T.value = 10 AND T.display IN (?, ?);"
and then call
statement.setString(1, "Sample1");
statement.setString(2, "Sample2");
before executing the statement.
Update:
String generateParamString(int params) {
StringBuilder sb = new StringBuilder("(");
for (int i = 1; i < params; i++) {
sb.append("?, ");
}
sb.append("?)");
return sb.toString();
}
List<String> samples = ... // your list with samples.
String stmtString = "SELECT * FROM Table T WHERE T.value = 10 AND T.display IN "
+ generateParamString(samples.size());
// generate statement with stmtString
for (int i = 0; i < samples.size(); i++) {
statement.setString(i + 1, samples.get(i));
}
// execute statement...