Getting an error in update statement when accessing mysql from java - mysql

String sql = "update `library`.`memebers` set 'STATUS'='" + "1" +"' where mem_id = '"+str+"'";
int i = st.executeUpdate(sql);
Error in 2nd line above:
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 ''status' = '1' where mem_id = '656597'' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2618)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1749)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1666)
at Frames.Addmembers.jButton1ActionPerformed(Addmembers.java:181)
at Frames.Addmembers.access$000(Addmembers.java:21)
at Frames.Addmembers$1.actionPerformed(Addmembers.java:83)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Field name in single quotes. It should be either without quotes, or inside back single quotes: ```:
String sql = "update library.memebers set `STATUS`='1' where mem_id = '"+str+"'";

status is the name of a column, and as such, it should be either status or `status`.
Entities are either written plain, or they're quoted with ``. (Backticks, not apostrophes.)
Unless you're using reserved field names for column names (which you shouldn't do), you do not have to quote fields.
String sql = "update library.memebers set STATUS = 1 where mem_id = " + Integer.valueOf(str);
Note that I removed the quotes around the status and the mem_id. I'm assuming that both are integer fields, and if they are, you should not be quoting their values. Integer fields should have integer values, not strings that evaluate to integer values. (Note though that you would never want to just blindly assume a string is an integer and concatenate it into a query -- always make certain it's a proper integer first)

Related

Spark JDBC MySQL Syntax Error with column names with spaces

I'm querying a MySQL table using PySpark JDBC. The problem I'm facing is that said table has column names with spaces.
In MySQL Workbench I would do the query like this to get the data and that works fine.
select
`some id`
from
table
But when I do it via PySpark like this:
query = 'select `some id` from table'
df = sqlContext.read.format('jdbc') \
.options(
driver = 'com.mysql.jdbc.Driver'
, url = some_connection_url
, dbtable = query
, user = user
, password = password
).load()
I get the following error message:
Py4JJavaError: An error occurred while calling o497.load.
: java.sql.SQLSyntaxErrorException: 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 'select
`some id`
from
some_table WHERE 1=0' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:61)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation$.getSchema(JDBCRelation.scala:210)
at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:35)
at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:318)
at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:223)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:211)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:167)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
at py4j.Gateway.invoke(Gateway.java:282)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:238)
at java.lang.Thread.run(Thread.java:748)
I've tried quoting the column names with [] and "" but I get the same error message.
I'm also using the latest MySQL jars: mysql-connector-java-8.0.21.jar and Spark 2.4.
Any insights are highly appreciated.
Enclose your query in brackets () then try to pass to read.format("jdbc").
Example:
query = '(select `some id` from table)e'
df = sqlContext.read.format('jdbc') \
.options(
driver = 'com.mysql.jdbc.Driver'
, url = some_connection_url
, dbtable = query
, user = user
, password = password
).load()

JDBC update database

i have a form and onClick listener i want to update some data on my database exception says that i have a syntax error but when i execute query at mysql console it works here is my code all variables are checked
String temp = itemList.getModel().getElementAt(itemList.getSelectedIndex()).toString();
PreparedStatement pt = supplies.con.prepareStatement("update prods set pquant = pquant + ? where pname = ?");
pt.setInt(1, Integer.parseInt(empsalary.getText()));
pt.setString(2, temp);
supplies.pst.executeQuery(temp);
Error
com.mysql.jdbc.exceptions.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 'DVD Verdatim' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3206)
at com.mysql.jdbc.Statement.executeQuery(Statement.java:1232)
at buy$1.actionPerformed(buy.java:62)
As the compiler mentioned, there is indeed a Syntax error in your SQL query. Try:
String temp = itemList.getModel().getElementAt(itemList.getSelectedIndex()).toString();
PreparedStatement pt = supplies.con.prepareStatement("update prods set pquant = #0 + 21" + "'variableForPquant'" "where pname = #1" + "'variableForPname'");
pt.setInt(1, Integer.parseInt(empsalary.getText()));
pt.setString(2, temp);
supplies.pst.executeQuery(temp);
You need to use quotes when you are using variables in your SQL query. I believe it is either
"'variableName'" or '"variableName'"
I found my error i declare a variable pt and i execute the query from the statement that is empty pst i change to pt.executeUpdate(); and its ok now

Update table using GUID

I am using MySQL with ASP.NET/VB. In a table I use GUID instead of int identifiers. All goes as planned until I try to update a specific row, where I get a syntax error in the statement below:
Dim q As String = "UPDATE documents SET date_document = #date_document, document_type = #document_type, sender = #sender, receiver = #receiver, description = #description, document_number = #document_number, pages = #pages, handled_date = current_timestamp, handled_user_id = #handled_user_id, error_code = #error_code) WHERE id = #id"
My GUID parameter:
.Parameters.Add("#id", MySqlDbType.Guid, 16).Value = myguid
And the error:
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 ') WHERE id = '8873442f-2f0b-4372-ac08-8388220c6eca'' at line 1
Any ideas on what's going on?
You're chasing down the wrong issue. What character does your error syntax begin with? It starts off as ') Where id = ...
You're assuming it's the id. It's not. That works fine. The first character is a closing parenthesis. That's the clue. There is no opening parenthesis. Remove the ) because you don't need it with an update statement.

(ColdFusion + Access) Database Query Error "Too few parameters."

I'm about to rip my hair out with this one.
Error Executing Database Query.
[Macromedia][SequeLink JDBC Driver][ODBC Socket][Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 3.
The error occurred in [WITHHELD]: line 19
17 : WHERE FNAME = #FORM.first#
18 : AND LNAME = #FORM.last#
19 : AND PASS = #FORM.pass#
20 : </cfquery>
21 :
SQLSTATE 07002
SQL SELECT * FROM JUDGES WHERE FNAME = [WITHHELD] AND LNAME = [WITHHELD] AND PASS = [WITHHELD]
VENDORERRORCODE -3010
DATASOURCE honors
I've read a number of similar issues where there was some spelling error but I've checked and rechecked spellings, even changed column and table names and tried again.
Ensure that you quote your variables:
where FNAME = '#FORM.first#'
Additionally, you should really use cfqueryparam to protect against SQL injection attacks:
where FNAME = <cfqueryparam value="#FORM.first#" cfsqltype="CF_SQL_VARCHAR">
(Note that you do not need the quotes when using cfqueryparam)
cfqueryparam documentation
a note about MS Access support for cfqueryparam

How do I write instructions to compare fields like `Date` and `Time` in SQL with `Date` and `Time` as parameters?

I have the following Java code to access DB2 to find if a record exists:
public static boolean isMailStored(Connection connection, Date giornogiorno,Time oraora) {
try {
System.out.println("oraora: "+oraora);
String CHECK_MAIL = "select count(*) from x.MAILDAIMAP where MNROMAIL = ";
CHECK_MAIL = CHECK_MAIL + oraora;
System.out.println("Statement: "+CHECK_MAIL);
ResultSet rs=st.executeQuery(CHECK_MAIL);
The System.out.println displays:
oraora: 10:27:20
Statement: select count(*) from x.MAILDAIMAP where MORAMAIL = 10:27:20
COM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver][DB2/NT] SQL0104N an unespected token ":27" was detected after "where MORAMAIL = 10". The tokens provided may include: "CONCAT". SQLSTATE=42601
at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.throw_SQLException(Unknown Source)
at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.throw_SQLException(Unknown Source)
at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.check_return_code(Unknown Source)Error...
at COM.ibm.db2.jdbc.app.DB2Statement.execute2(Unknown Source)
at COM.ibm.db2.jdbc.app.DB2Statement.executeQuery(Unknown Source)
at parthoOriginale.Email.isMailStored(Unknown Source)
at parthoOriginale.ReadMail.processMessages(Unknown Source)
at parthoOriginale.ReadMail.main(Unknown Source)
MORAMAIL is defined as Time in DB2. Why does this error occur? How do I write instructions to compare fields like Date and Time in SQL with Date and Time as parameters?
Think of Date and Time fields as really just being String/Varchar fields with constraints on the format. When querying against them, treat your comparison values as string, i.e. put them in quotes.
CHECK_MAIL = CHECK_MAIL + "\"" + oraora + "\"";