Can't insert data into data base - mysql

i have written a code to insert data in data base its is
String sql="INSERT INTO check (name,pass,pno) VALUES (?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, pass);
pstmt.setInt(3, no1);
pstmt.executeUpdate();
As i have avoided the sql injection and used preparedstatement i am still getting this error in my server log:
SEVERE: 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 'check (name,pass,pno) VALUES ('Nikhil Muskur','qwerty1',7898455)' at line 1
i double checked it as nothing is wrong with the syntax then what is the problem can anybody help

check is a reserved word in MySQL: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Change your query to:
String sql="INSERT INTO `check` (`name`, `pass`, `pno`) VALUES (?,?,?)";
so MySQL understands you are actually accessing a table.

('Nikhil Muskur','qwerty1',7898455) : update query by ('Nikhil Muskur','qwerty1','7898455')
7898455 must be an string value.

Related

How to use the parameterized MySQL query for "LOAD DATA LOCAL INFILE..." statement that accepts the values from variables?

I need to make the MySQL query "LOAD DATA LOCAL INFILE..." statement as parameterized SQL Query that accepts the value from variable. But unable to resolve it. The query along with C# code is given as below:
The SQL used is:
const string TableNameParam = "#tablename";
const string FieldDelimiterParam = "#fieldDelimiter";
const string ColSqlParam = "#colSql";
var sqlQuery = $"LOAD DATA LOCAL INFILE '{FilePathParam}'
INTO TABLE {TableNameParam} FIELDS TERMINATED BY '{FieldDelimiterParam}' {ColSqlParam}";
cmd.CommandText = sqlQuery;
cmd.Parameters.AddWithValue(FilePathParam, filePath);
cmd.Parameters.AddWithValue(TableNameParam, tableName);
cmd.Parameters.AddWithValue(FieldDelimiterParam, fieldDelimiter);
cmd.Parameters.AddWithValue(ColSqlParam, colSql.ToString().ToUpper());
cmd.ExecuteNonQuery();
It throws the same exception with 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 '? FIELDS TERMINATED BY '#fieldDelimiter' ?' at line 1
It seems like the SQL syntax error, but picking & mapping the individual value from the parameters does not give any syntax error.
Similarly, I have also tried by using the StoredProcedure for the same as below:
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#filePath", filePath);
cmd.Parameters.AddWithValue("#tablename", tableName);
cmd.Parameters.AddWithValue("#fieldDelimiter", fieldDelimiter);
cmd.Parameters.AddWithValue("#colSql", colSql.ToString().ToUpper());
cmd.ExecuteNonQuery();
The StoredProcedure used is as below:
CREATE PROCEDURE `sp_AggregateReport_LoadData`(
IN filePath VARCHAR(255), IN tablename VARCHAR(50),
IN fieldDelimiter VARCHAR(5), colSql VARCHAR(2500)
)
BEGIN
SET #sqlQuery= CONCAT("LOAD DATA LOCAL INFILE '",filePath,"' INTO TABLE ", tablename," FIELDS TERMINATED BY '",fieldDelimiter,"' ",colSql);
PREPARE stmt FROM #sqlQuery;
EXECUTE stmt;
END
It throws the exception with message:
This command is not supported in the prepared statement protocol yet
Does anyone having the same issue previously using the parameterized MySQL query? Need help.

PARSE_ERROR MySQL

These lines give me the parse error, ı checked my syntax many times but it seems alright to me. I don't understand why does it give this error
code:
INSERT INTO club_request(RequestID,"Besiktas")
SELECT RequestID
FROM Request
WHERE RequestName = "New goalkeeper";
error:
ER_PARSE_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 '"Besiktas") SELECT RequestID FROM Request WHERE RequestName = "New goalkeeper"' at line 1
INSERT INTO club_request(RequestID, ClubName)
SELECT RequestID, ClubName
FROM Request, Club
WHERE RequestName = "New goalkeeper" AND ClubName = "Besiktas";
lately I have turned it into this and now it works as I wanted, can't we insert partial value from select clause and partial value as a string ?

You have an error in your SQL syntax (but there is no error) [duplicate]

This question already has an answer here:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: error in SQL syntax
(1 answer)
Closed 4 years ago.
JDBC gave me this error.
Grave: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'INSERT INTO entitytwitterusertofollow
VALUES(0,NULL,NULL,1018880775335436288,F' at line 2
I have a huge Java String with a thousands of lines like this :
INSERT INTO `entitytwitterusertofollow` VALUES(0,NULL,NULL,984815801063571456,FALSE,1);
INSERT INTO `entitytwitterusertofollow` VALUES(0,NULL,NULL,1018880775335436288,FALSE,1);
INSERT INTO `entitytwitterusertofollow` VALUES(0,NULL,NULL,845199742065827841,FALSE,1);
INSERT INTO `entitytwitterusertofollow` VALUES(0,NULL,NULL,1018871764624035840,FALSE,1);
INSERT INTO `entitytwitterusertofollow` VALUES(0,NULL,NULL,811280845638090752,FALSE,1);
INSERT INTO `entitytwitterusertofollow` VALUES(0,NULL,NULL,1018804045635641344,FALSE,1);
INSERT INTO `entitytwitterusertofollow` VALUES(0,NULL,NULL,1018784953839038464,FALSE,1);
But if I debug, view my String, save it in a file, and then import it in MariaDB, everything is fine.
What's wrong with JDBC?
I was using bad code actually...
In JDBC, we should use addBatch(sql); the perform this kind of operation.
for (...) {
final String sql = "INSERT INTO `entitytwitterusertofollow` (ENTITYUSERID, ENTITYTWITTERCONCURRENT_ID) VALUES("+ id + "," + concurrent.getId() + ");";
statement.addBatch(sql);
}
statement.executeBatch();
conn.commit(); // if needed

Unknown SQL syntax error for ScalikeJDBC with SQL interpolation

To avoid DRY, I'm attempting to create an sql INSERT statement with variable column names and the data to fill those columns via ScalikeJDBC's sql interpolation:
case class MySQLInsertMessage(tableName:String, columns:List[String], values:List[String])
def depositMessage(msg: MySQLInsertMessage): Unit = {
NamedDB('MySQLMsgDepositor) localTx { implicit session =>
val sqlStmt = sql"INSERT INTO ${msg.tableName} (${msg.columns}) VALUES (${msg.values})"
println("The sql statement is: " + sqlStmt.statement)
println("The parameters are: " + sqlStmt.parameters)
sqlStmt.update().apply()
}
}
And when I call this with:
depositMessage(MySQLInsertMessage("My_Table", List("key", "email"), List("42", "user#email.com")))
the resulting console printout is:
The sql statement is: INSERT INTO ? (?, ?) VALUES (?, ?)
The
parameters are: List(My_Table, key, email, 42, user#email.com)
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 ''My_Table'
('key', 'email') VALUES ('42', 'user#emai' at line 1
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 ''My_Table' ('key', 'email') VALUES
('42', 'user#emai' at line 1
I've tried wrapping the sql"..." as such instead:sql"""...""", but that doesn't seem to make a difference. I can execute the expected statement just fine in my MySQL workbench GUI. Any idea what my syntax error is?
Stemming from the hint from #scaisEdge, it seems ScalikeJDBC, when using its syntax, will always place single quotes around any parameterized values. And judging from here - https://github.com/scalikejdbc/scalikejdbc/issues/320 - this is a known issue.
With a MySQL INSERT statement (or others), your table name or column values may not have single quotes around them, though they are allowed to have backticks.
You can use their SQLSyntax.createUnsafely(str:String) method, or, if I wanted to do this as I was doing above, instead of using sql"...", I could use the old way of SQL(s"INSERT INTO ${msg.tableName} (${msg.columns.mkString(",")})")
Note - I believe both of these leave you open to injection attacks. Since, for me, this is a local API and you'd have to have the DB's username and password regardless to use it, I'm going with the createUnsafely way of doing things, with a little regex "cleaner" for a little inelegant piece of mind:
def depositMessage(msg: MySQLInsertMessage): Unit = {
NamedDB('MySQLMsgDepositor) localTx { implicit session =>
val unsafeSQLRegex = "[`'\"]".r
val table = SQLSyntax.createUnsafely(s"`${unsafeSQLRegex.replaceAllIn(msg.tableName, "")}`")
val columns = SQLSyntax.createUnsafely(msg.columns.map(value => unsafeSQLRegex.replaceAllIn(value, "")).mkString("`", "`, `", "`"))
val sqlStmt = sql"INSERT INTO $table ($columns) VALUES (${msg.values})".update().apply()
}
}
}

MySQL syntax error when executing SQL query

When I try to run the code below I am getting:
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`
String query="Select * from DB.Admin where username = ?";
PreparedStatement st=connection.prepareStatement(query);
st.setString(1,request.getParameter("loginid"));
ResultSet rst= st.executeQuery(query);
int count=0;
while(rst.next()){
count++;
}
Please help me in this.
You will have to remove the query argument from your executeQuery call. If you provide the parameter, the query will be executed without binding any values (see Statement for details) - this is why the syntax (i.e. the ?) is invalid.
Execute the query like this:
ResultSet rst = st.executeQuery();
As a side note: you should always wrap Connection, PreparedStatement and ResultSet with a try-with-resources block, e.g.
try (ResultSet rst = st.executeQuery()) {
// read the results
}
This way you can be sure the ResultSet will be closed no matter what happens.