I write this query and it has error what is problem?
prepare test from
'select * from ?';
what is problem?
what is it's correct form?
You can't just put a placeholder wherever you like. Parameter placeholders can appear only in those places inside the statement where you would normally expect an expression. In particular, you cannot use parameter placeholders to parameterize identifiers or entire statement structures. That's why your attempt fails.
Many more useful things regarding prepared statements and Dynamic SQL in MYSQL can be found in Roland Bouman's blog -> MySQL 5: Prepared statement syntax and Dynamic SQL.
If your intended use is something like:
prepare test
from
'select * from ?' ;
set #myt := 'myTable' ;
execute test
using #myt ;
it will simply not work. But you can bypass it with:
set #myt := 'myTable'
set #qtext := concat('select * from ',#myt) ;
prepare test
from #qtext ;
execute test ;
I've never tried having the table name as a variable. I'm not sure that's allowed. Try the following:
PREPARE test FROM "SELECT * FROM table_name WHERE column = ?";
This is kind of a stab in the dark, since you're not providing the error message.
Related
Im trying to secure my store procedure to avoid SQL Injection attacks using prepared
statements. with the guide that mentioned here :
"https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html"
mysql> PREPARE stmt1 FROM 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
mysql> SET #a = 3;
mysql> SET #b = 4;
mysql> EXECUTE stmt1 USING #a, #b;
+------------+
| hypotenuse |
+------------+
| 5 |
+------------+
mysql> DEALLOCATE PREPARE stmt1;
I have no problem with passing parameter one by one.
Now if i have to pass array of item to SP from java and use 'where..in' , what is the best
approach ?
I can use something like this :
SET #somestring = '1,3,18,25';
SET #s=CONCAT("
SELECT * FROM city
WHERE id IN (",#somestring,");");
PREPARE stmt FROM #s;
EXECUTE stmt;
Dont know if is it secure enough for injection , since i guess its not checking parameter
one by one while it not use "USING #a, #b".
You cannot pass an array to your stored procedure, because MySQL doesn't support arrays. Your string '1,3,18,25' is a string that happens to contain commas. This is not an array.
Interpolating an unknown string into a dynamic SQL statement is SQL injection, full stop. You can't be sure it does not contain special characters that would change the syntax of the dynamic SQL query, so it's not safe.
The safest way to use variables in dynamic SQL statements is by using query parameters. But there's a couple of problems: I assume your string with comma-separated numbers may have a variable number of numbers, and you must support that.
Query parameters can only be used for individual scalar values. One parameter per value:
WHERE id IN (?, ?, ?, ?)
The syntax for EXECUTE stmt USING ... supports a variable number of arguments, but not a dynamic number of arguments. You must code the arguments as fixed in your code, and the arguments must be individual user-defined variables (the type with the # sigil). There's no good way to convert a string of comma-separated values into a like number of individual variables. It's possible to extract substrings in a loop, but that's a lot of code.
And it still wouldn't help because you'd have to find a way to pass a dynamic number of arguments to EXECUTE ... USING.
A common workaround for MySQL users is to use FIND_IN_SET(). This allows you to match a column to a comma-separated string of values.
WHERE FIND_IN_SET(id, '1,3,18,25') > 0
So you could pass your string as a single parameter to a prepared statement:
SET #somestring = '1,3,18,25';
SET #s='SELECT * FROM city WHERE FIND_IN_SET(id, ?)';
PREPARE stmt FROM #s;
EXECUTE stmt USING #somestring;
In fact, you don't even need to use PREPARE & EXECUTE for this. You can use MySQL variables in a query directly.
SELECT * FROM city WHERE FIND_IN_SET(id, #somestring);
This is safe, because the variable does not cause SQL injection. The query has already been parsed at the time you create the stored procedure, so there's no way the content of the variable can affect the syntax of the query, which is what we're trying to avoid.
This is safe ... but it's not optimized. By using FIND_IN_SET(), the query cannot use an index to search for the values in your string. It will be forced to do a table-scan. Probably not what you want.
So what are the options for solutions?
You could check the input string to make sure it has only digits and commas, and abort if not.
IF #somestring NOT REGEXP '^([[:digit:]]+,)*[[:digit:]]+$' THEN
SIGNAL SQLSTATE VALUE '45000'
SET MESSAGE_TEXT = 'Invalid input, please use only comma-separated integers';
FI
Once you confirm that the string is safe, then you can safely interpolate it into the query string, as in your example with CONCAT().
My preferred solution is to stop using MySQL stored procedures. I hardly ever use them, because virtually every other programming interface for MySQL is easier to code.
set #switch_schema= concat('use ', v6_schema, ';');
select #switch_schema;
PREPARE s3 from #switch_schema;
EXECUTE s3;
Prepare statement does not support 'Use'; is there a solution to this?
The workaround is the following but I am looking for a more robust solution
set #db := v6_schema;
drop temporary table if exists tempdb.activeUnits;
set #query = concat ('create temporary table tempdb.activeUnits
select *
from ',#db,'.activemodelunits_blue
where active_datetime = (Select max(active_datetime) from ',#db,'.ActiveModelUnits_blue) ';
PREPARE s3 from #query;
EXECUTE s3;
I'm afraid since you can't run USE as a prepared statement, your options are limited.
USE before you call this routine
You could call USE from your application before calling the procedure where you reference the table.
USE v6_schema;
CALL MyProcedure();
USE inside a CASE
If you are writing this code in a stored procedure, you can use the CASE statement.
BEGIN
CASE v6_schema
WHEN 'myschema1' THEN USE myschema1;
WHEN 'myschema2' THEN USE myschema2;
WHEN 'myschema3' THEN USE myschema3;
ELSE USE mydefaultschema;
END CASE;
END;
This means you're limited to the finite list of schemas for which you have coded. You can't make this adapt to any future schema name you think of in the future, without updating the code.
Use qualified table names
This is the workaround you mentioned in your question. Concatenate the schema name with table names, every time you reference those tables in prepared queries.
Lets say that I want to write a procedure allowing me to call certain function on certain column, for example:
call foo('min','age') -> SELECT min(age) FROM table;
I want my procedure to be safe from sql injection, therefore, I'm willing to use prepared statements and parametrize the input
SET #var = "SELECT ?(?) FROM table;"
PREPARE x FROM #var;
EXECUTE x USING a, b;
Where a and b are input parameters, function and column, respectively.
However, it doesnt seem to be possible - InnoDB keeps throwing an error whenever I want to execute this statement.
Is it possible to solve this this way, or I need to resort to whitelisting?
EDIT:
Full code:
create procedure test(in func varchar(20), in col varchar(20))
begin
set #f = func;
set #c = col;
set #sql = "select ?(?) from table;";
prepare x from #sql;
execute x using #f, #c;
end;
calling:
call test('min','age');
Full error:
[42000][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 '(?) from table' at line 1
You cannot parametrize column/table/function name/alias. As, PREPARE statement only allow "values" part of the SQL query to be used as parameters. Function/Table/Column name/alias are used to determine the validity of the SQL statement; and thus cannot be changed during run-time execution. Changing it at execution time would potentially alter whether the SQL statement was valid.
You can think of it as compiling a code; hence the compiler must know all the function/class name(s) etc for creating a valid executable (yes, we can do dynamic classes, but that is rare). On the other hand, we can change input "values" to the program, but generally cannot change the operations to be done on the input data.
Also, MySQL server would consider the parameters as literals, and apply quotes around them, before using them in query execution.
Now, in your case, you can still use the function name as parameter for Stored procedure, and generate the query string using that. But you cannot use it as a parameter for the query itself.
delimiter $$
create procedure test(in func varchar(20), in col varchar(20))
begin
set #c = col;
-- use concat function to generate the query string using func parameter
set #sql = concat('select ', func, '(?) from table');
-- prepare the statement
prepare stmt from #sql;
-- execute
execute x using #c;
-- don't forget to deallocate the prepared statement
deallocate prepare stmt;
end$$
delimiter ;
I came across this while writing a mySQL query builder plugin. My solution was to prefix column and function names with a "?" character (the user can change the character in the plugin preferences).
The code that builds the prepared statement looks for values that begin with "?" and inserts the subsequent column/function name into the query inline instead of as prepared statement values.
I learned today through this section of the MySQL documentation that prepared statements cannot be performed in stored functions, but, as of MySQL version 5.0.13, they can be performed in stored procedures.
Today I was putting together a stored procedure and thought initially it might be interesting to try doing an INSERT statement in it as a prepared statement. However, despite this supposedly being possible (I'm using MySQL 5.5.14), the ? parameter marker in the statement string caused MySQL to throw a syntax error.
I threw a couple of simplified examples together using the same exact sort of syntax I used for the prepared INSERT statement. I'm hoping I just have a syntax error somewhere I just haven't caught. The first block, below, is the procedure that works, i.e. it uses the standard CONCAT(your query string) syntax.
DROP PROCEDURE IF EXISTS TestConc;
DELIMITER $$
CREATE Procedure TestConc()
BEGIN
SET #sql := CONCAT('CREATE TABLE Foo (FooID INT) ENGINE = InnoDB');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET #tn := 'Foo';
SET #sql := CONCAT('INSERT INTO ', #tn, ' VALUES (5)');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
$$
DELIMITER ;
Upon calling the procedure with this code, the expected happens; 5 is stored in the FooID field of the newly-generated Foo table. However, if we change the lines between the two DEALLOCATE PREPARE directives to this:
SET #tn := 'Foo';
SET #sql := 'INSERT INTO ? VALUES (5)';
PREPARE stmt FROM #sql;
EXECUTE stmt USING #tn;
We get an error that tells us to check the syntax of the statement near '? VALUES (5)'.
Is it just not possible to substitute a parameter marker for a table name? I haven't tried doing something along the lines of 'SELECT ? FROM Foo' to see if this will work yet. Also, and I don't know if it's important, I've been trying this using MySQL Workbench 5.2.35 CE, rather than a command line.
I don't have any specific need to run queries as prepared statements within procedures ATM, I just want to make sure I have the syntax correct for doing so if I ever should need to.
The parameter '?' cannot be used for identifiers. Use first variant. From the reference - Parameter markers can be used only where data values should appear, not for SQL keywords, identifiers, and so forth.
Is it just not possible to substitute a parameter marker for a table name?
No, it's not possible. If you ever think you need this feature, it could be a sign that you have a bad table design.
If you really need to specify the table at runtime, you can use dynamic SQL but be careful not to introduce SQL injection vulnerabilities.
DELIMITER $$
CREATE PROCEDURE `Insert1`(IN NAME VARCHAR(100),IN valuees VARCHAR(100))
BEGIN
SET #r = CONCAT('Insert into', NAME,'(name)','VALUES',valuees);
PREPARE smpt FROM #r;
EXECUTE smpt;
DEALLOCATE PREPARE smpt;
END$$
DELIMITER ;
it is successfully compiling...
but when i execute gives me problem...
**CALL Insert1('rishi','duyuu')**
Error Code : 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 'VALUESduyuu' at line 1
There are multiple problems, first see what query has the CONCAT function produced. You will notice that it's not a valid query - 'Insert intorishi(name)VALUESduyuu'. Next, see the documentation on PREPARE/EXECUTE and use a placeholder for the value. The string would need to be put into quotes and escaped if you want to produce a raw query string. So try something like this:
SET #r = CONCAT('INSERT INTO ', NAME, ' (name) VALUES (?)');
SET #v = valuees;
PREPARE smpt FROM #r;
EXECUTE smpt USING #v;
Btw, instead of asking a number of small questions here, maybe you should ask a more high level question, explain what you have tried, what failed, etc. It's easier to help you with high level issues, but if you are doing something the wrong way and ask small technical questions how to fix it so that it works the wrong way, it won't help you much.
Add spaces to the concatenation:
CONCAT('Insert into ', NAME,'(name)',' VALUES ',valuees);