Hi there i have this code which is having an error when i try to run it.
s.executeUpdate("UPDATE [salesRecord] SET [backOrder] = 'backOrder'," +
" [quantity] ='"+ conDiff +"'" +
"WHERE [productID] = '" + s1 +"' AND [orderNumber] = '"+valueOrder+"' " );
the purpose of this code is to set orders as back orders when all items are not delivered. i want to specify which product i will update by setting my where to look for that item using productID and orderNumber.
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]
Too few parameters. Expected 1.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
Above is the error that shows when i try to run the program.
Try the following
Let backOrder , conDiff , s1, valueOrder be the variables.
s.executeUpdate("UPDATE [salesRecord] SET [backOrder] = '"+backOrder+"',[quantity] ='"+ conDiff +"' WHERE [productID] = '" + s1 +"' AND [orderNumber] = '"+valueOrder+"' " );
The query you have written is not using any parameters, but the error message says it is expecting one. This means that your "s" is probably being reused from somewhere else before and, that is using a parameter.
Seeing as you are using Java, I assume s is a java.sql.PreparedStatement or similar and that a parameter has been set using any one of the s.setXXX(parameterIndex, value) methods.
more details see http://docs.oracle.com/javase/7/docs/api/index.html
The simple solution is to use new statement.
Related
String sqlInsertBeacon = "INSERT INTO `beacon` (zone_id, location) VALUE ('(SELECT id FROM zone WHERE GeographicalID = '" + geometry3 + "')', Point(" + x_coordinate + "," + y_coordinate + "))";
System.out.println("The SQL query is: " + sqlInsertBeacon); // Echo for debugging
int countInserted3 = stmt.executeUpdate(sqlInsertBeacon);
System.out.println(countInserted3 + " records inserted.\n");
When I run the above code, the build is successful but the program stops when it reaches the execute line. I am entering using this sql query to insert data into a mysql database. I am not sure where the error is in my query? Can anyone suggest an alternative way or find the mistake?
The output of the program is this, as you can see the program, stops running after the second line:
The SQL query is: INSERT INTO table
(zone_id, location)
VALUES
((SELECT id FROM zone WHERE GeographicalID = '6311599'), Point(-121.9453802,37.3256131) )
;
BUILD SUCCESSFUL (total time: 6 seconds)
For additional information incase it helps:
The stmt, is created like this:
try (
// Step 1: Allocate a database 'Connection' object
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/adhwere2?useSSL=false", "root", "your_new_password"); // MySQL
// Step 2: Allocate a 'Statement' object in the Connection
Statement stmt = conn.createStatement();) {
and the catch exception is :
} catch (SQLException ex) {
}
Try something like this:
String sqlInsertBeacon = "INSERT INTO `beacon` (zone_id, location)" +
" VALUES ( (SELECT id FROM zone WHERE GeographicalID = '" + geometry3 + "'), Point(" +
x_coordinate + "," + y_coordinate + "))";
Just removed the apostrophes aroung the inner SELECT and replaced VALUE with VALUES...
The problem was because the sub-query was returning more than one result, and printing out a stack trace helped debug this error. Using Limit 1 in the sub query also solved this issue.
please use query according to this syntax:
INSERT INTO table
(column1, column2, ... )
VALUES
(expression1, expression2, ... ),
(expression1, expression2, ... ),
...;
your table name is in single quotes and its VALUES not value mind these small things
Correct INSERT INTO SELECT statement looks like this:
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
And you can use PreparedStatement to set parameters in your query.
I am facing a problem usign JPA, and more specifically using a IN clause.
The best way is, I think, to show you my code :
#NamedQuery(name = "Commande.findCustom", query = "SELECT DISTINCT [myFields] "
+ "FROM Commande c WHERE "
+ "[SomeCriterias] AND "
+ "c.ID IN (SELECT t.ID FROM SubTable t "
+ "WHERE t.IDX IN :param) AND [otherCriterias]"),
I then get an error from MySQL :
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 '.ID FROM SubTable t1 WHERE (t1.IDX IN (168)'
I am looking for a response but can't find anything ...
I tied to delete a IN clause, the problem is still the same (so it's not a double IN use problem)
my :param is a List of objects, that i got by using the Object.find() method. As you can see, it returns the ID (168). But I can't seem to find the problem ...
Any help would be greatly appreciated, thank you
EDIT : Full query
#NamedQuery(name = "Commande.findCustom", query = "SELECT DISTINCT c.idChargement, c.libelle, "
+ "c.codeTransporteur, c.reference, c.dateCreation, c.dateChargementPrevu, "
+ "c.dateValidationChargement, c.dateLivraisonPrevue, c.codeDestinataire, "
+ "c.raisonSocialeDestinataire, c.adresseDestinataire, c.codePostalDestinataire, "
+ "c.villeDestinataire, c.paysDestinataire, c.contactDestinataire, "
+ "c.telephoneDestinataire, c.mailDestinataire, c.poidsCommande, c.nombreColis, "
+ "c.nombreUniteManutention, c.typeUniteManutention, c.prendreRDV, c.commentaires "
+ "FROM Commande c WHERE "
+ "c.idChargement = :idChargement AND c.codeTransporteur = :codeTransporteur AND "
+ "(c.dateCreation BETWEEN :dateDebut AND :dateFin) AND "
+ "c.idDernierStatut IN (SELECT l.idListeStatutsCommande FROM Listestatutscommande l "
+ "WHERE l.idStatut IN :idStatut) AND c.raisonSocialeDestinataire = :raisonSociale AND "
+ "c.adresseDestinataire = :adresseDestinataire AND c.codeDestinataire = :codeDestinataire "
+ "AND c.codePostalDestinataire = :codePostal AND c.villeDestinataire = :villeDestinataire "
+ "AND c.paysDestinataire = :codePays")
And the Error 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 '.idListeStatutsCommande FROM listestatutscommande t1 WHERE (t1.IdStatut IN (168)'
As you are getting error from MYSQL not Hibernate, you could try to find out what query actually is generated. To do this, use proxy invoker like p6spy and then everything should be clear. Check p6spy site. When you do, try to invoke such generated SQL yourself and try to fix it. I used such method when I had some troubles using JPA's joins fetches and stuff. Very helpfull in diagnosing such problems.
Ok so I found the problem, and then the answer. Thanks #Antoniossss, the fact is that I was looking at the wrong part of the query.
The error was here : c.idDernierStatut IN ...
The fact is that this part is a foreign key. And when you want to search on it, you have to consider it as an object. So the correct form is c.idDernierStatut.idListeStatutsCommande IN to get the ID.
Thank you to both of you for your time anyway !
Is it possible to insert a from field in a update query?
i need it because before update something,i need to do some controls.
p.s i know that i have to use prepared statement but i want to know this error,i suppose it is a missing quote,that i can't see.
the 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 'from warehouse,product where warehouse.idProduct=shop.idProduct and warehouse.id' at line 1
int rs = st.executeUpdate("UPDATE shop SET quantity='"
+ Quantity
+ "' from warehouse,product where
warehouse.idProduct=shop.idProduct and
warehouse.idProduct=product.id and product.brand='"
+ Brand + "' and product.productType='" + Product
+ "'");
That just isn't valid SQL. UPDATE statements cannot have a FROM clause.
Single-table syntax:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
Multiple-table syntax:
UPDATE [LOW_PRIORITY] [IGNORE] table_references
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
I think you want an update with a join:
UPDATE shop s join
warehouse w
on w.idProduct = s.idProduct join
product p
on w.idProduct = p.id and
p.productType = '"+Product+"' and
p.brand = '" + Brand + "'
SET s.quantity = "+ Quantity
As a note. I'm guess that Quantity is numeric. If so, you don't need quotes around the value.
So I am coding in Java, using JDBC with SQL to get data from a database. I cannot chnage the data or the column names in the database. Everything worked perfectly until I was told today that another column of the database was needed.
So I tried to add the column name to the select statement, however I get an error:
"java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 2."
Here is the variable and name for the column: String est = "\"Estimates Complete?\"";
So after LOTS of research, it seems that there is something called "Bind Variables" in JDBC and ? happens to be one of them. I keep finding forum posts and answers on how to create Bind Variables, but nothing on how to "Escape" them. I cannot change the value of the Estimates Complete? column, and it is needed for my program.
If I try String est = "Estimates Complete?";, then the error I get is:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect
Anyone know if it is possible? Thanks.
Edit: Code example:
Statement s = conn.createStatement();
String tableName = "\"Open WRs V2\"", data1 = "\"Project Name\"",est = "Estimates Complete?";
String selTable = "SELECT " + data1 + "," + est+ " FROM " + tableName;
s.execute(selTable);
ResultSet rs = s.getResultSet();
while ((rs.next())) {
String name = (rs.getString(1));
String estimate= rs.getString(2);
System.out.println("test: "+estmate);
}
s.close();
can you replace the ? with chr(63) like in the answer here :
How to avoid ODBC parameterization for the question mark character ? within literals and comments?
Im working with MySQL in java.
I'm trying to update the 'owners' field in one of the tables 'regApartmentsTable', 'gardApartmentsTable', 'penthousesTable', which is empty, and corresponds to specific apartmentNum and street, and replace it with the string 'newOwners'.
In order to do that I've wrote the following code:
st=connection.prepareStatement("UPDATE regApartmentsTable,gardApartmentsTable,penthousesTable SET owners=? " +
"WHERE owners=? AND apartmentNum=? AND street=?");
st.setString(1, newOwners);
st.setString(2, "");
st.setInt(3, apartmentNum);
st.setString(4, streetName+" "+buildingNum);
I include the 3 tables since I need to look in all of them. (The required apartment, which has no owners, and matches the apartmentNum and street, cannot be in more than one table, if it helps anyone).
But, when I try to run this code, I get a "Column 'owners' in field is ambiguous" error.
Any ideas how else should I write the SQL command ?
thanks ahead!
EDIT:
I didn't get a sufficient answer to my problem... Ok, I understood that the exception raises since 'owners' field is common in those three tables.
And yet, how do I solve the problem? I cannot add a prefix with the table's name since I do not know in which table I'm going to find the required apartment... If I knew so, I wouldn't have searched in 3 tables.
The multiple tables UPDATE in MySQL is just a form of table join, using regApartmentsTable.owners and such.
You need a separate UPDATE for every table here, as a join is not what you intend for the update. Or make a base table.
str = connection.prepareStatement("UPDATE regApartmentsTable SET owners=? " +
"WHERE owners=? AND apartmentNum=? AND street=?");
str.setString(1, newOwners);
str.setString(2, "");
str.setInt(3, apartmentNum);
str.setString(4, streetName+" "+buildingNum);
str = connection.prepareStatement("UPDATE gardApartmentsTable SET owners=? " +
"WHERE owners=? AND apartmentNum=? AND street=?");
stg.setString(1, newOwners);
stg.setString(2, "");
stg.setInt(3, apartmentNum);
stg.setString(4, streetName+" "+buildingNum);
stp = connection.prepareStatement("UPDATE penthousesTable SET owners=? " +
"WHERE owners=? AND apartmentNum=? AND street=?");
stp.setString(1, newOwners);
stp.setString(2, "");
stp.setInt(3, apartmentNum);
stp.setString(4, streetName+" "+buildingNum);