MySQL syntax error when executing SQL query - mysql

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.

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.

MySQL Syntax with FROM with a var

I got some problems with my MySQL Syntax.
This is my code:
Config.SocietyMoneyTable = 'addon_account_data'
local result = MySQL.Sync.fetchAll("SELECT money FROM #account_table WHERE account_name = #society", {
['#account_table'] = Config.SocietyMoneyTable,
['#society'] = society
})
Error:
[ERROR] [MySQL] [maze_management] An error happens on MySQL for query "SELECT money FROM
'addon_account_data' WHERE account_name = 'society_police'": ER_PARSE_ERROR: 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 ''addon_account_data' WHERE account_name = 'society_police''
at line 1
The Syntax does work when I change the #account_table to the string which is in Config.SocietyMoneyTable. But I need this configed so this is no solution for me.
A query parameter annotated with the # sigil can only be used in place of a scalar value, not a table name or other identifier. You need to use string formatting to get your configurable table name into the query, not a query parameter.
Something like the following:
Config.SocietyMoneyTable = 'addon_account_data'
local queryString = string.format("SELECT money FROM `%s` WHERE account_name = #society",
Config.SocietyMoneyTable)
local result = MySQL.Sync.fetchAll(queryString, {
['#society'] = society
})
I have not tested this code, and I don't use Lua often, so if there are mistakes I will have to leave it to you to resolve them. But it should at least show the principle: identifiers (like table names) must be fixed in the query string, not added as query parameters.

I cannot make binding work with Diesel on MariaDB

I simply wanted to pass an argument to my sql query.
let query = sql("SELECT resa_comment FROM reservation WHERE resa_id = ? ");
let query2 = query.bind::<Integer, _>(1286);
let result : Result<std::vec::Vec<String>, _> = query2.load(&connection);
dbg!(result);
But the result is
[src/bin/show_posts.rs:36] result = Err(
DatabaseError(
__Unknown,
"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 \'?\' at line 1"
)
)
The SQL query is correct because when I replace the "?" with a constant and remove the "bind", I get a correct result.
I know that I can map the table to a Rust structure but my goal is to pass complex requests with arguments so I was testing Rust and Diesel.
Is there something I missed ? Thanks.
The bind method does not replace question mark, it appends the value to the end of the query. So it should look like this:
let query = sql("SELECT resa_comment FROM reservation WHERE resa_id = ");
// ...
If you need to put value in the middle of the query, then you need to chain bind and sql calls, such as:
sql("SELECT resa_comment FROM reservation WHERE resa_id = ")
.bind::<Integer, _>(1286)
.sql(" AND something > ")
.bind::<Integer, _>(1);
But note that you should avoid writing raw sql if it is not necessary.

Can't insert data into data base

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.

Simple difficulty with HQL Query

I am having a trouble with executing an HQL query like this:
select new myPackage.view.CoverDocumentReportView(Re.code AS fulCd,
Re.creditPrice AS crtprc,
Re.debitPrice AS dbtprc,
(Re.debitPrice - Re.debitPrice) AS redbtprc,
(Re.creditPrice- Re.creditPrice) AS recrtprc,
(Re.debitPrice-Re.creditPrice) AS rem)
from
(select fullCode as code,
sum(creditPrice) as creditPrice ,
sum(debitPrice) as debitPrice
from DocumentMaster DM,
DocumentAccount DA,
Tree T ,
AccountTree AT,
DocumentDetailed DD
where DM.id = DA.documentMaster and
DA.accountTree = T.id and
DA.accountTree = AT.id and
DD.documentAccount = DA.id
group by DA.accountTree ) As Re
1)
If I execute this like:
SQLQuery crit = (SQLQuery) session
.createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(CoverDocumentReportView.class));
ArrayList<CoverDocumentReportView> li = (ArrayList<CoverDocumentReportView>) crit.list();
ERROR 2012-12-22 14:16:19,838 [http-8080-1] org.hibernate.util.JDBCExceptionReporter : 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 '.datx.web.accounting.view.CoverDocumentReportView(Re.code AS fulCd,
Re.creditP' at line 1
2)
If I execute it with this:
Query query = session.createQuery(sql).setResultTransformer(Transformers.aliasToBean(CoverDocumentReportView.class));
ArrayList<CoverDocumentReportView> li = (ArrayList<CoverDocumentReportView>)query.list();
The error will be:
ERROR 2012-12-22 14:51:46,709 [http-8080-1] org.hibernate.hql.ast.ErrorCounter : line 1:224: unexpected token: (
ERROR 2012-12-22 14:51:46,709 [http-8080-1] org.hibernate.hql.ast.ErrorCounter : line 1:308: unexpected token: sum
What is the problem?
SQL and HQL are two different languages.
HQL doesn't support subqueries in from clauses, so this query can't be an HQL query.
And SQL doesn't know about Java objects, and doesn't have any new() function allowing to create them, so the query is not a valid SQL query either.
Make it a valid SQL query, execute it using createSQLQuery(), then iterate through the results and create instances of your objects from the returned rows. Or use a result transformer as you're doing, which will do that for you. the result transformer will use the aliases you assigned to the returned columns of the SQL query to create beans for you. You don't need any new CoverDocumentReportView() in the query to make that work. Read the javadoc for details.