MySQLSyntaxErrorException when setting strings - java

I have a strange problem. When I execute the query in the following piece of code it throws a MySQLSyntaxErrorException with the message:
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
''fantasy' SET Quantity = 3 WHERE BookName = 'The Silmarilion'' at line 1
Code:
private void updateDBTable(String category, Vector dataVector) {
try {
for(int i = 0; i < dataVector.size(); i++) {
String bookName = String.valueOf(((Vector) dataVector.elementAt(i))
.elementAt(0));
int quantity = (int) ((Vector) dataVector.elementAt(i))
.elementAt(4);
statement = databaseConnection
.prepareStatement("UPDATE ? SET Quantity = ? WHERE BookName = ?");
statement.setString(1, category);
statement.setInt(2, quantity);
statement.setString(3, bookName);
statement.executeUpdate();
}
}
But if I write it in this way :
private void updateDBTable(String category, Vector dataVector) {
try {
for(int i = 0; i < dataVector.size(); i++) {
String bookName = String.valueOf(((Vector) dataVector.elementAt(i))
.elementAt(0));
bookName = "'" + bookName + "'";
int quantity = (int) ((Vector) dataVector.elementAt(i))
.elementAt(4);
statement = databaseConnection
.prepareStatement("UPDATE " +
category +
" SET Quantity = ? WHERE BookName = " +
bookName);
statement.setInt(1, quantity);
statement.executeUpdate();
}
}
It works fine. Can you help me to figure out why the syntax in the first example is wrong?

In the first case, you have also provided the table name as a parameter. Prepared statements take the column names as parameters. You need to provide the table name in the statement while using prepareStatement

Related

JAVA - MySQL an ArrayList

I have query from MySQl
String sqlSearch = "SELECT * from Item"
and method with ArrayList
public static ArrayList<String> checkNo() throws SQLException {
ArrayList<String> no= new ArrayList<String>();
DbManager db = new DbManager();
db.connect();
String sql = "SELECT * from Category where id = " + idUser + " ";
Statement stmt = db.connect().createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
no.add(rs.getString("nameCategory"));
}
db.disconnect();
return no;
}
And I get from specific user his category in arraylist, but how to pass this category to sqlSearch???
SELECT * from Item where category ????
data from ArrayList
Any idea?
You could loop through the ArrayList items and build a String to use in the where clause like this
String inCondition = "";
boolean first = true;
ArrayList<String> categories = checkNo();
for(String cat : categories){
if(first){
first = false;
} else {
inCondition += ",";
}
inCondition += cat;
}
String sqlSearch = "SELECT * from Item where category in (" + inCondition + ")";
Your checkNo() method return an ArrayList. It looks like this ArrayList will have only one item, get that item from the ArrayList and pass it to the query like this.
String category = list.get(i);
"Select * from Item where category = "+category;
As your query is not clear am giving you a sample code,jus try it
if (count > 0) {
for (int i = 0; i < count; i++) {
ColumnName= no.get(i).getColumnName();
}
getItemQuery = "FROM Item where category in (" +ColumnName + ")";
}
There are many ways of doing this,
one way is two combine two queries:
SELECT * from Item where category in (SELECT nameCategory from Category where id = idUser )
as suggested its better to use prepared statement.

Before start of result set running multiple sql

I'm currently working on an application for a restaurant. The idea for the code I'm currently working on is that it gets the name from a combobox and inserts a receipt into the database whith the employee number of the person who is working on it. The code whith which I'm trying to do it is:
RestaurantOrder sqlRestaurantOrder = new RestaurantOrder();
ActionListener printReceiptListner;
printReceiptListner = (ActionEvent) -> {
int ID = Integer.parseInt(input1.getText());
try {
SystemManager manager = new SystemManager();
ResultSet rs = manager.stmt.executeQuery(sqlRestaurantOrder.setIdSql(ID));
while (rs.next()) {
double totalPrice = rs.getDouble("sumprice");
if (ID > 0) {
Receipt receiptSql = new Receipt();
String firstName = (String) cb.getSelectedItem();
String checkoutDate = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
ResultSet rs2 = manager.stmt.executeQuery(receiptSql.getEmployeeId(firstName));
int employeeId = rs2.getInt("id");
while (rs2.next()) {
Receipt receiptSql2 = new Receipt();
ResultSet rs3 = manager.stmt.executeQuery(receiptSql2.SetStatusReceipt(employeeId, checkoutDate, ID, totalPrice));
while (rs3.next()) {
}
}
}
}
} catch (SQLException k) {
JOptionPane.showMessageDialog(null, k.getMessage());
}
};
The statements are:
public class Receipt {
public String sql;
public String sql2;
public String getEmployeeId(String firstName){
return sql2 = "SELECT id FROM employee WHERE firstName = '" + firstName + "';";
}
public String SetStatusReceipt(int employeeId, String checkoutDate, int id, double totalPrice){
return sql = "INSERT INTO `receipt` (`employeeId`, `price`, `restaurantOrderId`, `checkoutDate`) VALUES (" + employeeId + " , " + totalPrice + ", " + id + ", " + checkoutDate + ");";
};
}
I'm getting the error before start of result set which I looked up what it means but I can't get it fixed at the moment. Help will be appreciated.
If I forgot to post more important code let me know I'll update it
You have to call ResultSet.next() before you are able to access the fields of that ResultSet. So you need to move your assignment of employeeId into your while loop:
while (rs2.next()) {
int employeeId = rs2.getInt("id");
From the documentation of ResultSet.next():
A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

PostgreSQL MAX aggregate function applied to strings and Java resultset

Hello and thank you for reading my post.
I have a PostgreSQL table "t" with a column "c" which type is "character varying(32)".
Values in this column look like this: "2014100605".
I am using the "MAX()" aggregate function to retrieve the maximum value in this column.
SELECT MAX(c) AS max FROM t;
In Java, if I prepare the query above, get a "resultSet" object and send it the getString("max") message, I get max = null.
If I send it the getInt("max") method instead, I get the result I'm expecting, something like "2014100605".
Is this normal behavior?
Am I really allowed to do this or is it by chance I'm getting the expected result?
Is "MAX()" actually using the lexicographical order?
Best regards.
A bit of Java code:
s_preparedSqlQuery =
"SELECT MAX(quotinv_nro) AS quotinv_nro_max "
+ "FROM imw_quotation_invoice "
+ "WHERE quotinv_type = ? "
+ "AND quotinv_nro LIKE '" + s_quotinvDate + "%'";
preparedStatement = m_connection.prepareStatement(s_preparedSqlQuery);
preparedStatement.setString(1, s_quotinvType);
resultSet = preparedStatement.executeQuery();
if(resultSet != null)
{
if(resultSet.next())
{
// s_quotinvNroMax = resultSet.getString("quotinv_nro_max");
n_quotinvNroMax = resultSet.getInt("quotinv_nro_max");
// if(s_quotinvNroMax == null)
if(n_quotinvNroMax == 0)
{
n_nbQuotinvsThisSameDate = 0;
return n_nbQuotinvsThisSameDate;
}
else
{
s_quotinvNroMax = Integer.toString(n_quotinvNroMax);
n_length = s_quotinvDate.length();
s_currentMaxNro = s_quotinvNroMax.substring(n_length - 1);
n_nbQuotinvsThisSameDate = Integer.valueOf(s_currentMaxNro);
}
}
}
If you are hitting on a unique Id column....
int maxID = 0;
Statement s2 = con.createStatement();
s2.execute("SELECT MAX(UniqueId) FROM MyTable");
ResultSet rs2 = s2.getResultSet();
if (rs2.next())
{
maxID = rs2.getInt(1);
}
If you are hitting on any other non-key column....
int maxID = 0;
Statement s2 = con.createStatement();
s2.execute("SELECT MAX(ColumnValue) FROM MyTable");
ResultSet rs2 = s2.getResultSet();
while (rs2.next())
{
maxID = rs2.getInt(1);
}

how to correctly MySQL "desc table" via java connectivity

I am actually building a project where the names of tables present in databases of mysql are displayed in a list in java.
user selects a table from a list and the description of that table in given using "desc tablename" command.
The problem is, it is supposed to get every field in table but it only gets first field. Below i have explained it more, but first heres my code-:
try {
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(i);
}
String z = jList2.getSelectedValue().toString();
try {
Class.forName("java.sql.DriverManager");
} catch (ClassNotFoundException e) {
timeget();
jTextArea4.append(now + ": " + "/ Failed in getting Driver \n Error Message: " + e.getMessage() + " / \n \n");
JOptionPane.showMessageDialog(this, e.getMessage());
}
DriverManager.getConnection("jdbc:mysql://localhost:" + GlobalParams.portvar + "/", "" + k, "" + j);
stmnt = (Statement) con.createStatement();
String query = "desc " + z;
jTextArea5.append(now + ": " + "/ desc " + z + "; / \n \n");
ResultSet rs = stmnt.executeQuery(query);
String[] cnames = {"Field", "Type", "Null", "Key", "Extra"};
tableModel.setColumnIdentifiers(cnames);
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
jTable1.setFillsViewportHeight(true);
if (rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}
catch(SQLException e){//some blabla}
Now for detailing into problem->
Say from the list, i select a table called "city". Originally, it has four fields- ID, Name, Population, CountryCode. But in my jTable, only "ID" appears.
the code...
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(i);
}
...is simply to remove fields of old table when a new table is selected from list.
Hope i clarified my prob.
Please help regarding this. Thanks.
the problem is in this
if (rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}
you are not continuing the loop
change the if loop to while loop
while(rs.next()) {
String field = rs.getString("Field");
String type = rs.getString("type");
String nullinfo = rs.getString("null");
String key = rs.getString("key");
String extra = rs.getString("extra");
tableModel.addRow(new Object[]{field, type, nullinfo, key, extra});
}

sql.exception: column not found

Hi guys can u tell me what is wrong with my code?
When I set my ResultSet as "SELECT * FROM Table1" it works perfectly,
also if it is "SELECT key, itemName, itemPrice, itemQuantity FROM Table1"
but when I try to use only one of them or two it prints out an error column not found.
My database is stored in MS Acceess. That's my main:
try (Connection cn = DBUtil.getConnection(DBType.MS_ACCESS);
Statement st = cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("SELECT Table1.key FROM Table1");) {
Table1.displayData(rs);
} catch (SQLException ex) {
DBUtil.processException(ex);
}
and that's Table1.java:
public class Table1 {
public static void displayData(ResultSet rs) throws SQLException {
// to print out my database
while (rs.next()) {
StringBuffer buffer = new StringBuffer();
buffer.append(rs.getString("key") + " ");
buffer.append(rs.getString("itemName") + " ");
double price = rs.getDouble("itemPrice");
DecimalFormat pounds = new DecimalFormat("£#,##0.00");
String formattedPrice = pounds.format(price);
buffer.append(formattedPrice + " ");
buffer.append(rs.getInt("itemQuantity") + " ");
System.out.println(buffer.toString());
}
}
}
Your result set will only contain the columns that you define in your select query. So if you do
rs.getString("itemName")
then you have to select that column in your query, which you don't
st.executeQuery("SELECT Table1.key FROM Table1")
^-----------------column missing
Do
st.executeQuery("select key, itemName, itemPrice, itemQuantity from Table1")
you should use
buffer.append(rs.getString("Table1.key") + " ");
resultset have the data with name which you have given in select query.(key=Table1.key)

Categories