Manually sanitize SQL parameters - sql

I would like to run a script like:
CREATE LOGIN [me] WITH PASSWORD = #0
and run it like:
var createUserCommand = conn.CreateCommand();
createUserCommand.CommandText = script;
createUserCommand.Parameters.AddWithValue("#0", passwordDecrypted);
However, this throws:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near '#0'.
From what I read online (nowhere official, just from SO answers/comments) it is not possible to use SQL parameters with DDL statements. Link to official docs for this are welcome!
OK. I do need this parametrized. As I see it, there are 2 options:
I manually sanitize (.Replace("'", "''") => how can I do this best?
I call into .NET to sanitize for me. However I assume this is not sanitized within ADO.NET, but just past to SQL Server, and sanitized there...
What would be the best approach?

All you need to escape is the single ' to 2 x '
commandText = string.Format("CREATE LOGIN [me] WITH PASSWORD = '{0}'", pass.Replace("'", "''"));
An alternative would be to create a stored procedure with a password parameter and use it to build a CREATE LOGIN string which you then sp_executeSQL.

Related

How to insert special character in text area in C# & ASP.NET MVC?

I want to insert special characters in textarea of my ASP.NET MVC project but it cannot insert - I get an error
Syntax error near this 't
Please help me find a solution so I can complete my project as soon as possible.
It is highly recommended to use parameterized SQL when handling input from untrusted source. It not only fixes the special character problem but also prevents SQL Injection Attack:
using (MySqlCommand cmd = new MySqlCommand("insert into table_name(username)values(#username)", conn))
{
cmd.Parameters.AddWithValue("#username", username);
cmd.ExecuteNonQuery();
}
The error is coming from SQL syntax, not from C# . You add the ' it two times in a row to avoid the error
select 'test's' error
select 'test''s' runs

How do you retrieve the return value of a DB2 SQL sproc using Perl DBI?

I need to retrieve the value returned by a DB2 sproc that I have written. The sproc returns the number of rows in a table and is used by the calling process to decide whether or not to update other data.
I have looked at several similar questions on SO but they refer to the use of out parameters instead of using the sproc's return value, for example:
Perl Dbi and stored procedures
I am using a standard DBI connection to the database with both RaiseError and PrintError enabled.
$sql_stmt = "call MY_TABLE_SPACE.MY_SPROC('2011-10-31')";
$sth = $dbh->prepare($sql_stmt)
or die "Unable to prepare SQL '$sql_stmt': $rps_met_dbh->errstr";
$rsp = 0;
$rsp = $sth->execute();
unless($rsp) {
print(STDERR "Unable to execute sproc: $rps_met_dbh->errstr\n");
}
print(STDERR "$?\n");
I have tried looking at $h->err for both the statement handle and the db handle.
I would really prefer communicating the number of rows via a return code rather than using SQLSTATE mechanism if I can.
Edit:
I have finished up using a dedicated out parameter to communicate the number of rows updated as follows:
$sql_stmt = "call MY_TABLE_SPACE.MY_SPROC('2011-10-31')";
$sth = $dbh->prepare($sql_stmt)
or die "Unable to prepare SQL '$sql_stmt': $rps_met_dbh->errstr";
$sth = $dbh->bind_param_inout(1, $rows_updated, 128)
or die "Unable to prepare SQL '$sql_stmt': $rps_met_dbh->errstr";
$rows_updated = 0;
$rsp = 0;
$rsp = $sth->execute();
unless($rsp) {
print(STDERR "Unable to execute sproc: $rps_met_dbh->errstr\n");
}
print(STDERR "$rows_updated\n");
Edit 2:
And now thinking about this further I have realised that I should apply the PragProg principle of "Tell. Don't Ask." That is, I shouldn't call the sproc. then have it give me back a number before I decide whether or not to call the anopther sproc, i.e. "Ask".
I should just call the first sproc. and have it decide whether it should call the other sproc or not, i.e. "Tell" and let it decide.
What is wrong with using an output parameter in your procedure. I've not got a working DB2 lying around right now or I'd provide an example but when I was using it I'm sure you can define output parameters in procedures and bind them with bind_param_inout. I cannot remember if a DB2 procedure can return a value (like a function) but if it can them using "? = call MY_TABLE_SPACE.MY_SPROC('2011-10-31')" would allow you to bind the output return value. If this doesn't work you could use a DB2 function which definitely can return a value. However, at the end of the day the way you get data out of a procedure/function is to bind output parameters - that is just the way it is.
I've no idea what you mean by "using SQLSTATE". I've also no idea what you mean by looking at $h->err as that is only set if the procedure fails or you cannot call the procedure (SQL error etc).

Executing the contents of a memo on a TADOQuery

I have a really long list of sql commands on a memo, when I try to execute it I get the following error:
Parameter object is improperly defined. Inconsistent or incomplete information was provided.
The code to execute it:
Query.SQL.Text := Memo1.Lines.Text;
Query.ExecSQL;
I have a vague idea that the error is caused due to the way the query content was added, so, here's how I'm doing it now:
1) Memo1.Lines.LoadFromFile('Patch.sql');
2) Proceed to the query commands
As you can see, the contents of the memo is loaded from a file. Is there any other way to successfully do this?
P.S.: I'm using Microsoft SQL 2008.
Thank you!
It looks like you're not using parameters, so set ParamCheck off
Query.ParamCheck := false;
If there is a colon ":" in a string in the SQL, the TADOQuery thinks it's a parameter

Oracle database connection string PLSQL compatibility

I'm using an application called Logi info. it requires a connection string to my oracle database. the connection works fine but in order to configure the connection to recive ref cursors from the database, I apparently need to add PLSQLRSet=1 to the end of the string. when I do that I recieve an error "invalid connection string"
Here is my connection string without plsqlrset=1
Data Source=SID; User Id=username; Password=password;
My concern is that PLSQLRSet=1 might be .NET paramater only. Can anyone shed some light on the issue.
Thanks
It appears that the PLSQLRset option is a feature of the OraOLEDB provider (per http://download.oracle.com/docs/cd/B10501_01/win.920/a95498/using.htm).
Therefore I would guess that you have to add Provider=OraOLEDB.Oracle to the connect string -- as shown in the screenshot on the page you linked to -- in order to use this option.

PHP error_log errors to MySQL

In a previous ticket i asked about logging PHP errors in MySQL which gives me:
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
// mysql connect etc here...
$sql = "INSERT INTO `error_log` SET
`number` = ".mysql_real_escape_string($errno).",
`string` = ".mysql_real_escape_string($errstr).",
`file` = ".mysql_real_escape_string($errfile).",
`line` = ".mysql_real_escape_string($errline);
mysql_query($sql);
// Don't execute PHP internal error handler
return true;
}
// set to the user defined error handler
$new_error_handler = set_error_handler("myErrorHandler");
I can make this work but only if it is triggerred like this:
trigger_error("message here");
However, I also want the error handler to be called for all errors such as syntax errors like:
echo "foo;
But these errors are just outputted to the screen, what am i doing wrong?
You can only handle runtime errors with a custom error handler. The echo "foo error in your example happens when parsing (i.e. reading in) the source. Since PHP can not fully parse the code, it can also not run your error handler on this error.
If You're forced to test if syntax is correct, You can use php_check_syntax function, with filename parameter PHP Manual php_check_syntax
php_check_syntax also provides second parameter, witch when used will be populated by the error string, as far as i remember
That's indeed terrible way of error logging
You don't need not a single advantage of a database. Would you make a database lookup for the certain line number? Or order your results by file name?
database is a subject of many errors itself.
You've been told already that it's impossible to catch a parse error at the program logic level, because a syntactically wrong program will never run.
Let's take your code as an example. It will raise a MySQL error (because of poorly formed query) which you will never see. As well as any other errors occurred. That's what I am talking about.