Select for nowait update - java

I have a customer that needs a large number of updates done in the database. I have finished trying to persuade them this can be done more cleanly. They want to run a select statement with a "for update nowait" on a select row and then you they want to run the update statement. I have tried this a number of ways but I am getting errors.
String selectQuery = " Select * from " + table + " where column=\'" + column + "\' FOR UPDATE NOWAIT";
String updateQuery = " UPDATE " + table + " SET newcolumn = \'" + newValue + "\' WHERE column = \'" + column + "\' ";
Connection connection = null;
try
{
connection = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
Statement stmt = connection.createStatement();
stmt.addBatch(selectQuery);
stmt.addBatch(updateQuery);
stmt.addBatch(commit);
int [] updateCounts = stmt.executeBatch();
stmt.close();
}
This gets exception:
invalid batch command: invalid SELECT batch command 0
26736 [Thread-11_DataConversion] ERRORDTL - [1424462365738]java.sql.BatchUpdateException: invalid batch command: invalid SELECT batch command 0
at oracle.jdbc.driver.OracleStatement.executeBatch(OracleStatement.java:4462)
at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:213)
at .BatchTokenizationAgent.executeJob(BatchTokenizationAgent.java:246)
at com.yantra.ycp.agent.server.YCPAbstractAgent.executeOneJob(YCPAbstractAgent.java:392)
at com.yantra.ycp.agent.server.YCPAbstractAgent.processMessage(YCPAbstractAgent.java:294)
at com.yantra.ycp.agent.server.YCPAbstractAgent.run(YCPAbstractAgent.java:160)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
I have also tried:
String selectQuery = " Select * from " + table + " where column=\'" + column + "\' FOR UPDATE NOWAIT; UPDATE " + table + " SET newcolumn = \'" + newValue + "\' WHERE column = \'" + column + "\' ";
Connection connection = null;
try
{
connection = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
Statement stmt = connection.createStatement();
stmt.execute(selectQuery);
stmt.execute(updateQuery);
stmt.close();
}
This gets exception:
java.sql.SQLSyntaxErrorException: ORA-00911: invalid character
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:439)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:395)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:802)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:436)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:186)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:521)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:194)
at oracle.jdbc.driver.T4CStatement.executeForDescribe(T4CStatement.java:853)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1145)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1267)
Can someone please point in the correct direction? Thank you so much. This is to be one time job and just needs to work with minimum work needed.

Related

Can't Update the SQL through Java

I'm trying to make CRUD (Create, Read, Update, Delete) to my projects. But it seems the "update" doesn't work. It keeps saying
java.sql.SQLSyntaxErrorException : You have an error in your SQL syntax; check the manual that coresponds to your MariaDB server version for the right syntax to use near "Number" = 0813874810 WHERE Name = "Gregory" at line 1)
What the solution for this?
Here is my code:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata", "root", "");
String sql = "UPDATE employeetab SET Name = '" + txtEmployeeName.getText()
+ "',Address = '" + txtEmployeeAddress.getText()
+ "',Gender = '" + gender_type
+ "',Phone Number = '" + txtEmployeePhone.getText()
+ "' WHERE Name = '" + txtEmployeeName.getText() + "'";
stm = conn.prepareStatement(sql);
stm.execute(sql);
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
Problem comes from the space in column Phone Number. To make it work you need to escape the column name with `.
UPDATE employeetab
SET Name = 'something',Address = 'some address',Gender = 'whatever',`Phone Number` = '000000000'
WHERE Name = 'something';
You should follow sql naming conventions, normally words in column names are separated by _. Your column name should be - phone_number.
Also, as mentioned in comments, you should not just add user input into sql queries, because you are leaving yourself wide open for sql injection.
You need to follow the naming conventions , their is space between 'Phone Number' column you should not write like this you need to add _ in between of this two.
try this :
String gender_type = null;
if (ButtonM.isSelected()){
gender_type = "Male";
}else if(ButtonFM.isSelected()){
gender_type = "Female";
}
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata","root","");
String sql = "UPDATE employeetab SET Name = ? ," +
" Address = ? ," +
" Gender = ? ," +
" Phone Number = ? ," +
" WHERE Name = ? ," ;
PreparedStatement pStmt = conn.prepareCall(sql);
pStmt.setString(1, txtEmployeeName.getText()+"");
pStmt.setString(2, txtEmployeeAddress.getText()+"");
pStmt.setString(3, gender_type+"");
pStmt.setString(4, txtEmployeePhone.getText()+"");
pStmt.setString(5, txtEmployeeName.getText());
pStmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
its cleaner and should work.

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.

Populating jTable from postgresql

I am doing java project in NetBeans 8 using databases and GUI.The problem is appearing when I search through the database and add the found values to JTable: all values are being added only to first column of JTable while I need them added separately to corresponding columns. I tried getColumnCount() and it also gave me 1 meaning that I have only one column. How to add database values to JTable's corresponding columns?
I've tried all the populating functions adviced here
My code:
jTable1 = new javax.swing.JTable();
String sql = "SELECT (flight_id, plane_name, dep_city, arival_city, date_month, date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats) FROM flight "
+ "WHERE (dep_city = '" + SearchFlight.getFromCity() + "' AND "
+ "arival_city = '" + SearchFlight.getToCity() + "' AND "
+ "date_month = '" + SearchFlight.getMonth() + "');";
PreparedStatement stat = conn.prepareStatement(sql);
ResultSet rs = stat.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs)
);
jScrollPane1.setViewportView(jTable1);
SearchFlight is a GUI class, and its methods return strings obtained in GUI.
DbUtils.resultSetToTableModel(rs)is a method in net.proteanit.sql.DbUtils;
So, it is expected that the data will be filled into 9 columns, hoewever it fills all the data into one column.
SELECT ( ... )
must be
SELECT ....
And better use the PreparedStatement as intended. Otherwise SQL injection still is possible. And try-with-resources closes the things under all circumstances.
String sql = "SELECT flight_id, plane_name, dep_city, arival_city, date_month, "
+ "date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats "
+ "FROM flight "
+ "WHERE dep_city = ? AND "
+ "arival_city = ? AND "
+ "date_month = ?";
try (PreparedStatement stat = conn.prepareStatement(sql)) {
stat.setString(1, SearchFlight.getFromCity());
stat.setString(2, SearchFlight.getToCity());
stat.setString(3, SearchFlight.getMonth());
try (ResultSet rs = stat.executeQuery()) {
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
}

Java MySQL ODBC PreparedStatement cutting off query

`I am having a problem with doing a PreparedStatement for Java ODBC MySQL. It seems to be cutting off the query, and giving a syntax error. I am not sure how to proceed, as I am only learning Java SQL at this point. I can't really do a self contained example because the problem involves databases, and it would get quite big.
The code with the problem is this..
public void insertEntry(
Hashtable<String, String> strings,
Hashtable<String, Integer> integers,
Date created, Date paid, boolean enabled)
throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://" + dbHost + "/" + dbName +
"?user=" + dbUser + "&password=" + dbPass;
connect = DriverManager.getConnection(dburl);
ps = connect.prepareStatement("INSERT INTO " + dbName + ".users INSERT " +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ;");
java.sql.Date SQLcreated = new java.sql.Date(created.getTime());
java.sql.Date SQLpaid = new java.sql.Date(paid.getTime());
System.out.println("Debug: SQLpaid = " + SQLpaid.toString());
ps.setBoolean(1, enabled);
ps.setString(2, strings.get("username"));
ps.setDate(3, SQLcreated);
ps.setDate(4, SQLpaid);
ps.setString(5, strings.get("alias"));
ps.setString(6, strings.get("password"));
ps.setString(7, strings.get("email"));
ps.setString(8, strings.get("bitmessage"));
ps.setString(9, strings.get("torchat"));
ps.setInt(10, integers.get("reputation"));
ps.setInt(11, integers.get("privacy"));
ps.setInt(12, integers.get("fpmport"));
ps.setString(13, strings.get("fpm-template"));
ps.executeUpdate();
ps.close();
connect.close();
resultSet.close();
}
I get the following output when trying to use this method...
Debug: SQLpaid = 1990-03-21
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorEx ception: 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 'INSERT enabled=0, username='default_username', created='2000-03-21', paid='1990-' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Construc tor.java:532)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:41 1)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:4169)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:26 17)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java :2778)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionIm pl.java:2834)
at com.mysql.jdbc.PreparedStatement.executeInternal(P reparedStatement.java:2156)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2441)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2366)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2350)
at database.Users.insertEntry(Users.java:297)
at test.dbUsers.main(dbUsers.java:95)
i think your doing some mistake in your code:
these are following as:
1. your mention INSERT and you should must change like SET
2. your adding the ;in your SQL Query you should remove that.
your code:
ps = connect.prepareStatement
("INSERT INTO " + dbName + ".users INSERT " #look here error to change 'set' +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ; " #remove this semicolon(;));
you should must change like as:
ps = connect.prepareStatement
("INSERT INTO " + dbName + ".users SET " +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ");
Change:
INSERT INTO " + dbName + ".users INSERT "
To:
INSERT INTO " + dbName + ".users SET "
Refer to:
MySQL: INSERT Syntax
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name,...)]
SET col_name={expr | DEFAULT}, ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]

Update Statement - Syntax error in UPDATE statement (Java & MS Access)

I am trying to update a MS Access database. I have searched this and I have tried everything I have found but I am still getting the following error.
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.
Any help would be very helpful. My code is below...;
String sqlStatement = "UPDATE ProductCatalogue"
+ "SET [StockLevel] = ?"
+ "WHERE [ProductID] = ?;";
PreparedStatement prepStatement = connection.prepareStatement(sqlStatement);
prepStatement.setInt(1, quantity);
prepStatement.setInt(2, productID);
//= "UPDATE ProductCatalogue"
//+ "SET StockLevel = " + quantity
//+ "WHERE ProductID = " + productID + ";";
try {
//myStatement.executeUpdate(sqlStatement);
prepStatement.executeUpdate();
} catch (SQLException sqle) {
System.out.println("Oopss...." + sqle);
}
connection.close();
prepStatement.close();
you may need a few whitespaces. Try:
String sqlStatement = "UPDATE ProductCatalogue "
+ "SET [StockLevel] = ? "
+ "WHERE [ProductID] = ?;";
(note the space after ProductCatalogue and the first ?)

Categories

Resources