I need help selecting within a MySQL DateTime range in Java - java

I've got the following code in my app
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = " + userId +
" AND InsertTimestamp BETWEEN " + lastDate +
" AND " + DataProcessor.TODAY + " ORDER BY UserId, Occurred";
try{
if(null == conn)
openDatabaseConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery(); <------- this is the line which throws the SQL exception
retArray = this.getArrayListFromResultSet(rs);
}catch(SQLException sqle){
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
So when I run my app in the debugger, I get this exception message
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 '00:00:00.0 AND 2014-08-20 00:00:00.0 ORDER BY UserId, Occurred' at line 1
I'm reasonably certain that there's simple and reasonable solution to this, but I have not been able to find it.
I've tried looking in the MySQL manual for a solution or a different format.
I've tried running my timestamps through a TIMESTAMP() functino and a DATE() function in the SQL, neither of which helped.
I pulled the fully formed SQL out of the Java code and ran it in MySQL Workbench with no issues, what-so-ever. So now I'm looking to the experts for help.

Dates in SQL must be enclosed within single quotes like strings.
As you're using a prepared statemtent, why you don't use '?' and stmt.setDate(...)?
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = ?" +
" AND InsertTimestamp BETWEEN ?" +
" AND ? ORDER BY UserId, Occurred";
try {
if(null == conn) {
openDatabaseConnection();
}
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
stmt.setDate(2, lastDate);
stmt.setDate(3, DataProcessor.TODAY);
ResultSet rs = stmt.executeQuery();
retArray = this.getArrayListFromResultSet(rs);
} catch(SQLException sqle) {
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
Anyway, I think you are setting the dates in the opposite order. You should put first 'today' then lastDate. Although I don't know your constraints...

Related

Getting unexpected Token error in sql query

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: TOP near line 1, column 8 [SELECT TOP 10 IServe.ID FROM TopUp.dbo.IServe WHERE ExpireDate >= '2019-10-03' AND TelcoID = '2' AND ProductID = '2' AND RechargeAmt = '100.0' AND Available = 1 ORDER BY ExpireDate, SN]
String query3 = "SELECT TOP " + importStockList.getOrderQuantity() +" IServe.ID FROM IServe WHERE "
+ " ExpireDate >= '" + sqlDate + "' " + " AND TelcoID = '" + importStockList.getTelcoId()
+ "' AND ProductID = '" + importStockList.getProductId() + "' AND " + "RechargeAmt = '"
+ importStockList.getRechargeAmt() + "' AND Available = 1 ORDER BY ExpireDate, SN" ;
Session hbsessionSQL = HibernateUtilSQL.getSessionFactory().openSession();
List<Iserve> iserve = hbsessionSQL.createQuery(query3).list();
Can you please help me this error. I am stuck here
While your query is hard to read, and you should be using a prepared statement, I don't see anything wrong per se about the syntax. So the error is probably happening because TOP is not valid HQL syntax. TOP is really only supported on Microsoft databases, such as SQL Server or Access. Try using LIMIT instead:
try {
Session session = HibernateUtilSQL.getSessionFactory().openSession();
Connection conn = session.connection();
String sql = "SELECT ID FROM IServe WHERE ExpireDate >= ? AND TelcoID = ? AND ProductID = ? AND RechargeAmt = ? AND Available = 1 ORDER BY ExpireDate, SN LIMIT ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDate(1, sqlDate);
ps.setInt(2, importStockList.getTelcoId());
ps.setInt(3, importStockList.getProductId());
ps.setInt(4, importStockList.getRechargeAmt());
ps.setInt(5, importStockList.getOrderQuantity());
ResultSet rs = ps.executeQuery();
while(rs.next()) {
// process result set here
}
}
catch(HibernateException e) {
e.printStackTrace();
}
Since its not understood what type your variables are, try to see the data by yourself. If there is an option string values contain special characters, remove them first.

Problem with Update query in Mysql with JDBC

see the screenshots
see the 2nd screenshot
see the 3rd screenshot
Okay so I am building a project on java and mysql, I am stuck at this point that I have to update a data which is in MySql but from my java gui application, I've executed that update command from MySql command line client
update user set bldu = 50 where userid = 1001;
and it's working perfectly fine there but from my java application on clicking on assigned jbutton it says:
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 'userid= 1001' at line 1
Please help me..!
In your first screenshot you must add a space before WHERE clause:
String query = "UPDATE user SET bdlu = " + bldut + "WHERE userid = " + uid + ";";
So your query will be interpretated as:
UPDATE user SET bdlu = 50WHERE userid = 1001
So you'll raise a syntax error.
Then you'll have the following query:
String query = "UPDATE user SET bdlu = " + bldut + " WHERE userid = " + uid + ";";
String query = "update user SET bldu = " + bldut + " WHERE userid = " + uid + ";";
use this one instead of your old query may be it is helpful for you.
Try this snippet in your code.
String query = "update user SET bldu = " + bldut + " WHERE userid = " + uid + ";";
Statement = con.prepareStatement(query);
Statement.executeUpdate();
by looking at your code you cannot store results of update query in resultSet the executeUpdate() only return 0 or 1 for success and failure of Update.
Okay i guys i have figured out something that it is working i mean this program is updating the data stored in mysql from netbeans via jdbc but it won't stop showing that error message like:
"Can not issue data manipulation statements with executeQuery()"
everytime i click one that assigned jButton..! but i checked the database the value i want to change is being changed but then why it is showing this error..?
Please use this code in your java file, do changes according to your file. your issue is you are using the same query in a result set that already uses for the update
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bdb", "root", "root");
try {
String query = "update user SET bldu = " + bldut+ " WHERE userid = " + uid + ";";
// create the java mysql update preparedstatement
Class.forName("com.mysql.jdbc.Driver").newInstance();
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.executeUpdate();
query = "select * from user WHERE userid = " + uid +";";
ResultSet rs = stmt.executeQuery(query);
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
String userid = rs.getString("userid");
String userfname = rs.getString("userfname");
// all your column
// Display values
System.out.print("userid: " + userid);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
} finally {
// finally block used to close resources
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}// end finally try
}// end try

Loading UUIDs from MySql database

i got a database where I use UUIDs as a primary key. I store the uuids as a binary(16) using java. To save an entry I use following
public boolean saveEntry(UUID id , String, name, int p1, int p2) throws SQLException
{
byte[] uuidBytes = new byte[16];
ByteBuffer.wrap(uuidBytes).order(ByteOrder.BIG_ENDIAN).putLong(id.getMostSignificantBits())
.putLong(id.getLeastSignificantBits());
String updateQuery = "INSERT INTO " + databaseTableName + " (ID, Name, p1, p2) "
+ "VALUES " + "(?, ?, ?, ?) "
PreparedStatement statement = null;
// write the id in the workflow table
statement = databaseConnection.prepareStatement(updateQuery);
statement.setBytes(1, uuidBytes);
statement.setString(2, name);
statement.setInt(3, p1);
statement.setInt(4, p2);
statement.execute();
This part is working and I can see my entries in the database.
However as soon as I try to load the entry with this:
public Workflow loadEntry(UUID id) throws SQLException
{
byte[] uuidBytes = new byte[16];
ByteBuffer.wrap(uuidBytes).order(ByteOrder.BIG_ENDIAN).putLong(id.getMostSignificantBits())
.putLong(id.getLeastSignificantBits());
String query = "SELECT " + "* " + "FROM " + databaseTableName + " WHERE " + databaseTableName
+ ".ID = ?";
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try
{
preparedStatement = databaseConnection.prepareStatement(query);
preparedStatement.setBytes(1, uuidBytes);
resultSet = preparedStatement.executeQuery(query);
I get following mistake:
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 '?' at line 1
I'm not quite sure what the cause pf the error is. I know that using id.toString().replaceAll("-", "") works, but I'm not sure about perfomance and functionallity of this way. So is there any way I can get around this Solution?

having error in WHERE clause of SQL query,

I am having an error in this code:
public List<AvailableTest> srchInTestsInDb(String search, String catg) {
try
{
Connection conn = Dbconn.Connect();
System.out.println(catg);
String sql = "SELECT * "
+ "FROM AVAILABLE_TESTS "
+ "WHERE TST_CATAGORY="+catg+"";
// + "TST_NAME LIKE '"+search+"%'";// AND TST_CATAGORY ="+catg+"";
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
List<AvailableTest> testList = new ArrayList<AvailableTest>();
while (rs.next())
{
AvailableTest newtest = new AvailableTest();
newtest.setTstNo(rs.getInt("TST_NO"));
newtest.setTstName(rs.getString("TST_NAME"));
newtest.setTstCatagory(rs.getString("TST_CATAGORY"));
newtest.setTstNormalValue(rs.getString("TST_NORMALVAL"));
testList.add(newtest);
}
return testList;
}
catch (SQLException ex)
{
Logger.getLogger(DbHandeler.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
Its output is:
chem
Jul 29, 2014 10:02:28 PM Db.DbHandeler srchInTestsInDb
SEVERE: null
java.sql.SQLSyntaxErrorException: ORA-00904: "CHEM": invalid identifier
When I print "catg" it prints "chem" which I need in my query, but it's not working.
It should be WHERE TST_CATAGORY='"+catg+"'", since a String parameter should be in quotes.
That said, that's a very bad practice, and you run the risk of SQL injection. Use a prepared statement :
String sql = "SELECT * "
+ "FROM AVAILABLE_TESTS "
+ "WHERE TST_CATAGORY=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString (1, catg);
ResultSet res = stmt.executeQuery ();;
Oracle is considering CHEM a column name since it isn't quoted. To get Oracle to treat it as a string, use single quotes.
String sql = "SELECT * "
+ "FROM AVAILABLE_TESTS "
+ "WHERE TST_CATAGORY='"+catg+"'";
Try:
String sql = "SELECT * "
+ "FROM AVAILABLE_TESTS "
+ "WHERE TST_CATAGORY='"+catg+"';";
Since the content of catg is a String it should also be in quotation marks (in the SQL-Query).

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