SQL Query using where clause in Prepared Statement [duplicate] - java

This question already has answers here:
How to add a where clause in a MySQL Insert statement?
(8 answers)
Closed 5 years ago.
I am working on a gate entry system, in which i am inserting in-time and out-time. While writing sql query for out-time, it is showing error at WHERE clause. I am not able to solve the error. What will be exact SQL query?
java.util.Date date = new java.util.Date();
java.sql.Timestamp sqlTime = new java.sql.Timestamp(date.getTime());
PreparedStatement ps = con.prepareStatement("insert into ENTRY(OUTTIME) values(?,?,?,?) WHERE (ENTRY.ROLLNUMBER='"+rollno+"' AND ENTRY.OUTTIME ='NULL')");
ps.setTimestamp(4,sqlTime);
ps.executeUpdate();

You need to UPDATE the existing row
PreparedStatement ps = con.prepareStatement("UPDATE ENTRY SET OUTTIME =? WHERE ROLLNUMBER=?");
ps.setTimestamp(1,sqlTime);
ps.setString(2, rollno);

This isn't how an insert statement works. If you want to update an existing record, you'd need an update statement:
PreparedStatement ps =
con.prepareStatement("UPDATE entry SET outtime = ? WHERE rollbumber = ?");
ps.setTimestamp(1, sqlTime);
ps.setInt(2, myRollNo);

It makes no sense for an insert statement to have a WHERE clause which refers back to the same record. I propose the following code:
java.sql.Timestamp sqlTime = new java.sql.Timestamp(date.getTime());
String sql = "INSERT INTO ENTRY(OUTTIME) VALUES (?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setTimestamp(1, sqlTime);
ps.executeUpdate();

Either you update or change your insert statement as below:
"insert into ENTRY(OUTTIME) select col1 from ENTRY WHERE ENTRY.ROLLNUMBER='"+rollno+"' AND ENTRY.OUTTIME ='NULL'"

Use this code
java.util.Date date = new java.util.Date();
java.sql.Timestamp sqlTime = new java.sql.Timestamp(date.getTime());
PreparedStatement ps = con.prepareStatement("update ENTRY set OUTTIME= ? WHERE ENTRY.ROLLNUMBER='"+rollno+"' AND ENTRY.OUTTIME is NULL");
ps.setTimestamp(4,sqlTime);
ps.executeUpdate();

Related

Query to select the sum of a column between two dates where some condition is true

ResultSet rs1 = state.executeQuery("select sum(bill_total) as bill_total"
+ " from t_report where date between ? and ? AND mode_of_payment='Cash' ");
PreparedStatement pst1 = conn.prepareStatement(sql);
pst1.setString(1, date1.getText());
pst1.setString(2, date2.getText());
while(rs1.next()){
cash_label.setText(rs1.getString("bill_total"));
}
I tried this Query but it's not working. I get error : Incorrect syntax near '?'
Out of the the two conditions only the payment method condition is working an the date condition is not working.
Can you try this :
pst1.setDate(1, new java.sql.Date(date1.getTime()));
pst1.setDate(2, new java.sql.Date(date2.getTime()));
I have tried something like this
Here is my database structure
CREATE TABLE bill_total2(bill_total integer,mode_of_payment string,date1 datetime);
/* Create few records in this table */
INSERT INTO bill_total2 VALUES(1,'cash','12-12-2016 00:00:00');
INSERT INTO bill_total2 VALUES(2,'cash','12-12-2016 00:00:00');
INSERT INTO bill_total2 VALUES(3,'cash','12-12-2016 00:00:00');
INSERT INTO bill_total2 VALUES(4,'cash','12-12-2016 00:00:00');
INSERT INTO bill_total2 VALUES(5,'cash','12-12-2016 00:00:00');
and my query is
SELECT sum(bill_total) FROM bill_total2
WHERE date1 BETWEEN '12-12-2016 00:00:00' AND '12-12-2016 00:00:00'
AND mode_of_payment='cash';
this is working fine for me.
You are executing the query before setting the parameters! Please try this:
String sql = "select sum(bill_total) as bill_total"
+ " from t_report where date between ? and ? AND mode_of_payment='Cash' ");
PreparedStatement pst1 = conn.prepareStatement(sql);
pst1.setString(1, date1.getText());
pst1.setString(2, date2.getText());
ResultSet rs1 = pst1.executeQuery();
while(rs1.next()){
cash_label.setText(rs1.getString("bill_total"));
}
try this query:
SELECT SUM(bill_total) AS bill_total FROM t_report WHERE (date BETWEEN to_date('01/01/2015','dd/mm/yyyy') and to_date('01/01/2017','dd/mm/yyyy') ) AND (mode_of_payment='Cash')

Calling a MSSQL stored procedure in Java

I have access to a stored procedure on a sql server which has one parameter and I can easily run it on the sql client as follow:
exec sp_name "2016/11/01"
Now I want to do the same thing in java.
PreparedStatement ps = conn.prepareStatement("sp_name ?");
ps.setString(1, "2016/11/01");
ResultSet rs = ps.executeQuery();
In rs I can see the columns' names, but zero row is returned. I think it is because of the stored procedure's parameter. Am I missing something here?
Here is the code that worked eventually:
String date= "2016/11/01"
String queryString "exec sp_dmp_pub_status ?";
PreparedStatement ps = conn.prepareStatement(queryString);
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date parsed = format.parse(date);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
ps.setDate(1, sqlDate);
ResultSet rs = ps.executeQuery();

what is wrong with the sql query in the java code

String sql = "UPDATE `test`.`books` SET ? = ? WHERE `isbn` = ?;";
PreparedStatement ps = null;
ps = conn.prepareStatement(sql);
ps.setString(1,whatToUp);
ps.setString(2, data);
ps.setString(3, isbn);
ps.executeUpdate(sql);
System.out.println("Statement executed");
conn.close();
Error say that something is wrong with query . I am usign MySQL 5.6.
I copied the statement from the workbench 6.0 and just placed ? wherever I needed.
Even this Gives an error:
String sql = "UPDATE `test`.`books` SET `title` = ? WHERE `isbn` = ?;";
PreparedStatement ps = null;
ps = conn.prepareStatement(sql);
ps.setString(1, data);
ps.setString(2, isbn);
ps.executeUpdate(sql);
System.out.println("Statement executed");
conn.close();
You can build the query dynamically
String sql = "UPDATE `test`.`books` SET " + whatToUp + " = ? WHERE `isbn` = ?;";
PreparedStatement ps = null;
ps = conn.prepareStatement(sql);
ps.setString(1, data);
ps.setString(2, isbn);
ps.executeUpdate(); // you need to use the overloaded method without an argument
Note that you are then vulnerable to SQL injection.
If for some reason that is wrong, remove all the quotes.
String sql = "UPDATE test.books SET " + whatToUp + " = ? WHERE isbn = ?;";
If that doesn't work, then your schema doesn't match. That's up to you.
In my rush to answer I didn't see you were using
ps.executeUpdate(sql);
This method's javadoc says
Note:This method cannot be called on a PreparedStatement or
CallableStatement.
You have to use
ps.executeUpdate();
since you've already provided the sql statement to the method.
All of this would've been solved extremely quickly if you had just provided the exception stack trace. Consider that next time you ask a question
The problem is that you are calling executeUpdate(String) on a PreparedStatement, for which the documentation says:
SQLException - [...], the method is called on a PreparedStatement or CallableStatement
You need to use executeUpdate() (so without parameters) to execute a PreparedStatement. The reason is: a prepared statement already knows its query (the one it was created with), so it makes no sense to provide a query when executing it.
Note that the MySQL implementation is not entirely conforming to JDBC. It actually does allow executing with a String here, but it causes a syntax error because of the parameter placeholders.
Your first piece of code will never work, because parameters can only be used in places of values, not in places where object names (like table names) are expected.
#SotiriosDelimanolis gave you the answer.
Just build the SQL String differently
Stringbuilder sql = new Stringbuilder("UPDATE test.books SET ");
sql.append(whatToUp);
sql.append(" = ? WHERE isbn = ?");
PreparedStatement ps = null;
ps = conn.prepareStatement(sql.toString());
ps.setString(1, data);
ps.setString(2, isbn);
ps.executeUpdate(sql.toString());
System.out.println("Statement executed");
conn.close();

Insert using PreparedStatement. How do I auto-increment the ID?

I have a PreparedStatement such as:
PreparedStatement preparedStatement = connect.prepareStatement("INSERT into employee (id, time, name" + "(?,?,?)",Statement.RETURN_GENERATED_KEYS);
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
preparedStatement.executeUpdate();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);
preparedStatement.setInt(1,autoGeneratedID);
preparedStatement.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(3, "Test");
preparedStatement.executeUpdate();
As you can see, the Employee table has an auto-incremented ID. I need to basically add it in automatically using preparedStatement as well. Can someone tell me where I am going wrong and correct me? Right now it just gives me an error related to Statement.
Leave the column out of the INSERT statement entirely. It will be generated by the database engine. Your query should be:
INSERT INTO employee (time, name)
VALUES (?, ?)
Secondly, you have to perform the insert first, then get the keys out of the result.
I believe your code should be:
PreparedStatement preparedStatement =
connect.prepareStatement("INSERT into employee (time, name) VALUES (?,?)",
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setTimestamp(1,
new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(2, "Test");
preparedStatement.executeUpdate();
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);
Note this example does not check the success of the executed statement or the existence of returned keys.
You should perform some modification(define default statement) to prepared statement string like this:
"INSERT into employee VALUES(default,?,?)"
That modification is because of occurring this problem : Column count doesn't match value count at row 1 JAVA mysql
After that you're code is something like below:
PreparedStatement preparedStatement =
connect.prepareStatement("INSERT into employee VALUES (default,?,?)", Statement.RETURN_GENERATED_KEYS);
preparedStatement.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(2, "Test");
preparedStatement.executeUpdate();
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
Thanks to Ic. for his answer.
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","password");
PreparedStatement ps = con.prepareStatement("insert into imgslider(id,cmnt,date1,img,status) values(seq.nextval,?,?,?,?)");
ResultSet rs = null;
String s1 = "I’ve Come and I’m Gone: A Tribute to Istanbul’s Street";
ps.setString(1,s1);
Calendar calendar = Calendar.getInstance();
java.sql.Date dd = new java.sql.Date(calendar.getTime().getTime());
ps.setDate(2,dd);
FileInputStream f1 = new FileInputStream("F:\\java\\slide-9.jpg");
ps.setBinaryStream(3,f1,f1.available());
ps.setInt(4,0);
int i = ps.executeUpdate();
System.out.println(i+" rows affected");
con.close();
}
here is my code for auto-increment column in table by PreparedStatement.

Convert Java Timestamp to MySQL timestamp vice versa

How can I Convert Java Timestamp (Timestamp data type) to MySQL timestamp vice versa?
If you're using the JDBC API to access the database, and you're using a PreparedStatement to for example execute an SQL INSERT statement, then you just set the timestamp as a parameter to the PreparedStatement:
Timestamp ts = ...; // wherever you get this from
PreparedStatement ps = connection.prepareStatement("INSERT INTO MYTABLE (ts) VALUES (?)");
ps.setTimestamp(1, ts);
ps.executeUpdate();
Likewise, when you're doing a query that returns a timestamp, get it from the ResultSet by calling getTimestamp on it. Example:
Timestamp result = null;
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT ts FROM MYTABLE WHERE ...");
if (rs.next()) {
result = rs.getTimestamp(1);
}
See the JDBC Tutorial.
Without more specifics on the trouble you are having, this will be a hard question to answer. However, Java makes this relatively straightforward if you are using prepared statements. Your code would look something like this:
Connection conn = getConnection();
PreparedStatement pStmt = conn.prepareStatement("UPDATE my_table SET my_column = ? WHERE id = ?");
pStmt.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
pStmt.setInt(2, 42);
pStmt.executeUpdate();
As far as I can see from MySQL docs, java.sql.Timestamp should just work if you read it from or write it to a TIMESTAMP field in the database. So you should not need to do any conversion.

Categories