I want to extract a text field from a database and insert it into some other database. So while extracting I used the REPLACE(message_text,'\'', '"') while selecting the test. I gave me an error. I changed that from my select statement and did it while initiating the global variable.
etl.globals['message_text'] = message_text;
still I'm getting an error at the insert statement
insert into lcs_al_user_likes(user_id,liked_user_id,post_content,loop_id) values('${etl.globals['posted_by']}','${etl.globals['liked_user_id']}','${etl.globals['message_text']}',?batchLoopCounter);
saying
*You have an error in your SQL syntaxcheck the manual that corresponds to your MySQL server version for the right syntax to use near 'message_text']}')' at line 1*
I think it is not getting the global variable. That I say because when i print its value using log it just gives me
${etl.globals['message_text']}
as output. So please help me out here.
<query connection-id="lcsDBConnection">
SELECT forum_topic_post_id AS forum_topic_post_id, posted_by AS posted_by,message_text as message_text FROM lcs_tbl_forum_topic_post WHERE like_count>0 LIMIT ?batchSize OFFSET ?queryCounter ;
<script connection-id="jexl">
etl.globals['forum_topic_post_id'] = forum_topic_post_id;
etl.globals['posted_by'] = posted_by;
etl.globals['message_text'] = message_text.replace('\'', '"');
</script>
It looks like the problem is in INSERT statement, you should use prepared statement
parameters escaping:
INSERT INTO lcs_al_user_likes(user_id,liked_user_id,post_content,loop_id) values(?{etl.globals['posted_by']},?{etl.globals['liked_user_id']},?{etl.globals['message_text']},?batchLoopCounter);
BTW As I understand, your original problem was quotes breaking the insert statement, so in this case with ?{parameter} syntax you don't need to use replace(...) function at all.
Related
I am trying to accomplish a simple licensing system in golang and have tried numerous ways to get it to work. Basically, I have input a couple of random licensing keys into my database and my golang program should check to see if the user-input key exists and if it does then add the user specified username and password into the database to login later.
This is the code that I have that hasn't been working:
"IF EXISTS (SELECT * FROM login WHERE LK = "+reglicenceEntry.Text()+") THEN
INSERT INTO `login` (`Username`, `Password`, `LK`) VALUES
('"+regusernameEntry.Text()+"', '"+regpasswordEntry.Text()+"', ''); "
This is the golang error:
Error 1064: 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 'IF EXISTS (SELECT * FROM login WHERE LK = '5qp515YHXEmSDzwqgoJh') THEN INSERT IN' at line 1
Thanks so much!
MySQL syntax doesn't support IF...THEN constructs except within stored routines and triggers and events. See https://dev.mysql.com/doc/refman/8.0/en/sql-syntax-compound-statements.html
I suggest an alternative solution for your code:
INSERT INTO `login` (`Username`, `Password`, `LK`)
SELECT ?, ?, ''
FROM `login`
WHERE `LK` = ?
LIMIT 1
If your login table does not have the LK value, the SELECT above will return 0 rows, therefore it will not insert anything.
If your login table has the LK value, the SELECT above will return at least 1 row (and I limit it to 1), therefore it will insert a row. The row it inserts is comprised of your username and password, and a blank string for the LK.
I showed use of parameter placeholders. You should use parameters in SQL instead of concatenating variables into your query. This is good practice to avoid accidental SQL injection. See http://go-database-sql.org/prepared.html for examples.
The purpose of using parameters is to avoid SQL injection problems. See my answer to What is SQL injection? for an explanation of SQL injection.
Or my presentation SQL Injection Myths and Fallacies (or youtube video).
When using parameters, you do two steps.
The first step to prepare a query with placeholders (?) where you would otherwise concatenate variables into your SQL query.
The second step is to execute the prepared query, and this is the time you pass the variables to fill in the placeholders.
The point is to keep variables separate from your query, so if there's anything in the variable that could unintentionally change your SQL syntax (like imbalanced quotes), it is never combined with the SQL. After you do the prepare, the SQL has already been parsed by the MySQL server, and there's no way to change the syntax after that.
MySQL remembers which parts of the query need to be filled in, and when you pass variables during the execute step, MySQL fills in the missing parts of the query using your values — but this happens within the MySQL server, not in your application.
Thus the dynamic parts of the query — your variables — are kept separate from the SQL syntax and you avoid SQL injection problems.
For your task described in your question, it would look something like this (I have not tested this Go code, but it should put you on the right path).
stmt, err := tx.Prepare("INSERT INTO `login` (`Username`, `Password`, `LK`) SELECT ?, ?, '' FROM `login` WHERE `LK` = ? LIMIT 1")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
_, err = stmt.Exec(regusernameEntry.Text(), regpasswordEntry.Text(), reglicenceEntry.Text())
if err != nil {
log.Fatal(err)
}
The order of parameters is important. The variables you pass to Exec() must be in the same order that the ? placeholders appear in your prepared SQL statement. They are matched up, one for one, in the same order, by the MySQL server.
Do not put quotes around the placeholders in your prepared SQL statement. That will work as a literal string '?' in SQL. Use an unquoted ? character for a placeholder. When it gets combined by MySQL in the server, it will work as if you had put quotes around the value like a string — but with no risk of SQL injection even if that string value containing special characters.
Here's another site that gives more code examples: https://github.com/go-sql-driver/mysql/wiki/Examples
The Exec() function is for executing SQL that has no result set, like INSERT, UPDATE, DELETE. There are other functions in the Go SQL driver like Query() and QueryRow() that also accept parameter arguments. You'd use these if your SQL returns a result set.
CREATE TABLE IF NOT EXISTS tmp_park_log (
uniqueid VARCHAR (20),
parked_sec INT
) ;
DELETE
FROM
tmp_park_log ;
INSERT INTO tmp_park_log (uniqueid, parked_sec)
SELECT
uniqueid,
SUM(parked_sec)
FROM
park_log
GROUP BY uniqueid ;
This is executing successfully in MySql:
But, when i put this in a string and use Prepared Statement it gives following 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 'DELETE FROM tmp_park_log; INSERT INTO tmp_park_log (uniqueid, parked_sec) SELEC' at line 1
SQL syntax for prepared statements does not support multi-statements (that is, multiple statements within a single string separated by “;” characters).
See here: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html
In the first case you arent using one commando instead you use a few commandos and when you put it in a string as a prepared statement you must create one prepared statement for every single commando you want to execute.
Since you didn't attached the Java code I assume you are
trying to d prepare statement for all the text and not to prepare every and execute it.
few hints:
There is no need to prepare the CREATE TABLE statement you can just use create statement and execute it (as no bind variables are used) http://docs.oracle.com/javase/tutorial/jdbc/basics/tables.html
If your application allows it , consider the use of truncate instead of delete, it will be faster and reduce the log generation.
Don't forget to commit :).
BR
I'm trying to write sql to insert a SQL code into one of the table's columns.
The table has these three columns: email, verification code, sql.
I try this code, and variations of it, playing around with the quotes and backslashing/escaping them, etc... but something's still wrong:
INSERT INTO pre_registration(email, verification_code, sql) VALUES('myemail#gmail.com', '8efb100a295c0c690931222ff4467bb8', '"INSERT INTO customer(title) VALUES(\'Mr.\')"')
It tells me there's an error in the SQL syntax:
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 'sql) VALUES('myemail#gmail.com', '89f0fd5c927d466d6ec9a21b9ac34ffa', "INSER' at line 1
How to do it? I'm using PHP/MySQL.
MySQL considers sql as a keyword. You have to quote it:
INSERT INTO pre_registration(email, verification_code, `sql`) VALUES('myemail#gmail.com', '8efb100a295c0c690931222ff4467bb8', '"INSERT INTO customer(title) VALUES(\'Mr.\')"')
By the way double the quotes to escape them instead of using bakslashes. This is more SQL friendly.
INSERT INTO pre_registration(email, verification_code, `sql`) VALUES('myemail#gmail.com', '8efb100a295c0c690931222ff4467bb8', '"INSERT INTO customer(title) VALUES(''Mr.'')"')
Some insight into the exact SQL error would help. At first glance I'd say you need to apply spaces between the table name and the open parentheses and between values and the open parentheses.
Also, the Single quotes around the double quotes for the SQL portion may be creating an error though I am not certain. Whatever is between the single quotes is interpreted literally which should make the escape characters actually be slashes inside the stored data.
Also, sql is a reserved word that must be quoted for use.
Finally, depending on your situation there may be a more secure method of data entry using prepare and bound parameters:
try
{
$conn = new PDO ( "sqlsrv:server = $serverstringname; Database = $logindatabase", "$loginusername", "$loginpassword");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
$email = 'myemail#gmail.com' //or some other way of setting the variable like $_POST
$verification_code = '#####' //or $_Post method
$sql = 'Put Query Here' //probably have to declare this explicitly
$sql_insert = "INSERT INTO pre_registration_info (email, verification_code, 'sql') VALUES (?,?,?)";
$stmt = $conn->prepare($sql_insert);
$stmt->bindValue(1, $email);
$stmt->bindValue(2, $verification_code);
$stmt->bindValue(3, $sql);
$stmt->execute();
I've been trying to update a field in MySQL database but I'm getting an error.
This is my Query
UPDATE tbl SET fl1="val",fl2="val", fl3="val" WHERE fl0="val val"
This is the error I received when I tried to execute the query
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 'val WHEREfl0="val val"' at line 1
I have removed the information from the query and replaced it with dummy text.
Taking a look at the error, I see 2 issues
val WHEREfl0="val val"
first of all, WHEREfl0 should probably be WHERE fl0
Secondly an issue here val WHERE[..] I think you are missing " there.
val" WHERE fl0="val val"
I am guessing you fixed the query while adding dummy text because this query is correct:
UPDATE tbl SET fl1="val",fl2="val", fl3="val" WHERE fl0="val val"
FOUND IT :D ... I'm having multiple queries to be executed, this is done using PHP ... The problem was in a query in the middle was like this:
UPDATE tbl SET fl1='val',fl2='val', fl3=''val WHERE fl0='val val'
THANK YOU ALL FOR YOUR SUPPORT.
Try using single quotes, not double. ('')
UPDATE tbl SET fl1='val',fl2=val', fl3='val' WHERE fl0='val val'
You should also use the "`" in your syntax:
UPDATE `tbl` SET `fl1`='val',`fl2`=val', `fl3`='val' WHERE `fl0`='val val'
how about this?
UPDATE `tbl`
SET `fl1` = 'val',
`fl2` = 'val',
`fl3` = 'val'
WHERE `fl0` = 'val val'
1.) I have changed Double Quote into Apostrophe.
2.) I added backtick in case one of your columns contains a reserved word.
The original query was:
UPDATE `test`.`documents` SET `title` = ‘测试中文’, `content` = ‘this is my test document number two,应该搜的到吧’ WHERE `documents`.`id` = 2;
Which resulted in:
#1064 - 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 test document number two,应该æ
I changed the wrong '
UPDATE 'test'.'documents' SET 'title' = '测试中文', 'content' = 'this is my test document number two,应该搜的到吧' WHERE 'documents'.'id' = 2;
and got:
#1064 - 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 ''test'.'documents' SET 'title' = '测试ä¸æ–‡', 'content' = 'this is my test do' at line 1
How do I set my my.ini?
I used XAMPP Lite, and MySQL version 5.1.37.
You're using ‘, instead of ', (that is, weird inverted commas)
For your new problem, you need to use `s (backticks) instead of ' (inverted commas) if you want to quote a table or column name.
Left and right single quotes (‘ and ’) should be replaced by normal apostrophe (').
Or is it called straight single quote?
Without knowing exactly where and how you're using that SQL statement, I can only guess that it could be an encoding problem. Try to change the encoding to UTF-8.
UPDATE test.documents
SET title = '测试中文',
content = 'this is my test document number two,应该搜的到吧'
WHERE documents.id = 2;
is also ok,and the same question is also my 3
all mysql table and field names should be escaped with backticks: `
all mysql strings should should be enclosed with single quote: '
try this:
UPDATE `test`.`documents` SET `title` = '测试中文', `content` = 'this is my test document number two,应该搜的到吧' WHERE `documents`.`id` = 2;
to address #3:
you need to alter the default charset for that table: "ALTER TABLEtest.documents. CONVERT TO CHARACTER SET utf8;" Be careful though, this may change the storage size requirements of the table, so if it's a large table, plan for the query to take a bit to execute.
to address #4:
you should add the following to the [mysqld] section of my.ini:
collation_server=utf8_unicode_ci
character_set_server=utf8