Insert into table using string in MySql - mysql

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

Related

Creating a procedure inside a query

I'm trying to implement a MySQL procedure (with if/else statements) inside a Granada query. The only issue is it won't let me create my procedure and call it from the same query...
ERROR
db query 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 'CALL tester(true)' at line 44
I'm confident the issue isn't with my syntax, but here's how the query looks:
CREATE PROCEDURE tester(
IN is_empty BOOLEAN
)
BEGIN
IF(is_empty) THEN
SELECT
...
from $dbName.table1
where KernelName IN ($KernelNameFilter) AND `gpu-id` in ($gpuFilter) AND `Index` in ($DispatchIDFilter)
union SELECT
...
from $dbName.table1
where KernelName IN ($KernelNameFilter) AND `gpu-id` in ($gpuFilter) AND `Index` in ($DispatchIDFilter)
ELSE
SELECT
...
from $dbName.table1
where KernelName IN ($KernelNameFilter) AND `gpu-id` in ($gpuFilter) AND `Index` in ($DispatchIDFilter);
END IF;
END;
CALL tester(true);
They seem to work on their own, but I have no idea why Grafana doesn't like this syntax. Any ideas?
NOTE:
Yes, it is necessary for me to create the procedure in Grafana query b/c I need to reference local Grafana variables (i.e. $KernelNameFilter, $gpuFilter, ...)
It's likely that you can't create procedure and call the procedure in a single call to the query interface. Most query interfaces do not support multi-query.
Even if the query interface supports multi-query, you can't use it to define a stored routine. Multi-query interfaces assume semicolon terminates the statement, so the first semicolon inside the body of your procedure would terminate the whole CREATE PROCEDURE statement. That's not what you want.
The MySQL client solves this by requiring you to change the statement terminator to something that doesn't appear in the body of the CREATE PROCEDURE statement. See https://dev.mysql.com/doc/refman/8.0/en/stored-programs-defining.html for details.
I need to reference local Grafana variables (i.e. $KernelNameFilter, $gpuFilter, ...)
You should make a procedure that takes your Grafana variables as parameters, and uses them in the queries within the procedure body — not create a brand new procedure each time you need to run the procedure.

How To resolve Syntax Error when using SQL Insert Into Select MySQL

I Have problem when using INSERT INTO SELECT function on mysql database, error is like this
the right syntax to use near 'INSERT INTO tmpProgkeg SELECT A.Tahun, 1, A.Kd_Urusan, A.Kd_Bidang, A.Kd_Un' at line 4
this Is Mysql Query
https://www.db-fiddle.com/f/tfVhWXC25EAQKHdpHv6VLU/0
i need help, thanks before...
Note that before your INSERT statement, you have a CREATE TEMPORARY TABLE statement:
CREATE TEMPORARY TABLE tmpProgkeg (
...
)
INSERT INTO tmpProgkeg SELECT ...
But you don't terminate the CREATE TEMPORARY TABLE statement with the required semicolon (;) character.
Each SQL statement must be terminated. For example:
CREATE TEMPORARY TABLE tmpProgkeg (
...
);
INSERT INTO tmpProgkeg SELECT ...
The requirement to terminate statements is similar to some other programming languages, for example C++, Java, or PHP.
Tip: When MySQL reports syntax errors, it shows you some portion of an SQL statement. It's telling you "I didn't expect the following code at the position you used it." It got confused because it was expecting some other code, the end of code, and it's showing you what it saw instead, following the point where it got confused.
So when you see
the right syntax to use near 'INSERT INTO ...
You know that you should look at your code right before that point, to see what you forgot.

MySQL code to insert a username and password into a table if a licencing key exists in that table

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.

Getting MySQL Error #1064 when trying to insert data

I'm trying to follow a tutorial on this website, but when I try to insert the below statement I get the following 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
'`INSERT INTO login_admin (user_name, user_pass)
VALUES
(
‘admin’, SHA(‘a`' at line 7
INSERT INTO login_admin (user_name, user_pass)
VALUES
(
‘swashata’, SHA(‘swashata’)
)
INSERT INTO login_admin (user_name, user_pass)
VALUES
(
‘admin’, SHA(‘admin’)
)
You're trying to run two queries at once, not one. Each INSERT statement is a separate query. You have to separate queries with a delimiter (;).
In fact, unless you have some bad settings on your server (allowing multiple queries at once), you can't even do that and need to run them as two separate queries, or combine them using multiple VALUES lists.
Also, please note that you cannot use tick marks (‘) to indicate a string value. You need to use single quotes (') instead.
The best approach is to rewrite your queries as:
INSERT INTO login_admin (`user_name`, `user_pass`) VALUES
( 'swashata', SHA('swashata') ),
( 'admin', SHA('admin') )
Finally, I really hope you aren't using SHA to generate passwords. That's not secure. Use PHP's built-in password functionality.

Special Characters in Scriptella, jexl

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.gl‌​obals['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.gl‌​obals['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.