What is wrong with my paramerized mysql statement in c#? - c#

When I try to execute this, I get an exception saying the syntax is incorrect?
string sql= string.Format(#"SELECT valueA
FROM tableA
WHERE columnA = #columnValueA");
var parameters = new MySqlParameter[1];
parameters[0] = new MySqlParameter("#columnValueA", string.Format("{0}","abc"));
foreach (var mySqlParameter in parameters)
{
cmd.Parameters.AddWithValue(mySqlParameter.ParameterName, mySqlParameter.Value);
}
//later I execute, it tells me the syntax is incorrect
-- I am trying to execute something on the database similar to below
SELECT valueA
FROM tableA
WHERE columnA = "abc"

do you need # in the MySqlParameter string? I would imagine you could do without it?

My query is correct, essentially, what was happening nested deeply within the code was it was appending an extra ) which was rendering the query syntax incorrect.

Related

Conversion failed when converting from string to uniqueidentifier - loading DataTable with ExecuteReader

In attempting to do a SQL query (which returns one string and one uniqueidentifier to columns 0 and 1 respectively) I get "Conversion failed when converting from a character string to uniqueidentifier" in my exceptions log. How can I avoid this? I'm assuming the issue is, the datatables columns are not defined, so it's expecting a string and SQL is trying to convert it. The exception is logged. Surprisingly to me the GUID is stored successfully to da[1]. So my program technically works, however I want to clear this exception and to do that I need to understand why it's happening and how to go about fixing it.
da = new DataTable();
da.Clear();
...
string invoiceStatusSQL = #"select status,invoice_id from invoices where acct_id='" + accountid + "'";
command = new SqlCommand(invoiceStatusSQL, cnn);
da.Load(command.ExecuteReader());
You should always parameterise your SQL queries to help prevent SQL injection and avoid problems like you're facing now. See Why do we always prefer using parameters in SQL statements?.
Use SqlParameter to add the parameters to the SqlCommand.
string invoiceStatusSQL = #"select status, invoice_id from invoices where acct_id = #accountId";
command = new SqlCommand(invoiceStatusSQL, cnn);
SqlParameter idParam = new SqlParameter("#accountId", accountid);
command.Parameters.Add(idParam);
da.Load(command.ExecuteReader());
You can also specify the actual database type when creating the parameter, which will reduce any issues you might have with the framework inferring the type incorrectly (although I don't think that would happen in your case for a Guid/UniqueIdentifier). One way to specify the type is shown below.
var p = new SqlParameter
{
ParameterName = "#accountId",
SqlDbType = SqlDbType.UniqueIdentifier,
Value = accountid
};

How to create Regex to validate logical AND OR operators in string [duplicate]

I am looking for a query validator in C#, which allows me to parse the SQL text from a textbox and verify whether it's correct or not before sending it for execution (MS SQL or DB2 queries).
If you want to validate SQL syntax without the use of a database, the TSql100Parser class will do well for this situation.
Disclaimer, code borrowed from this post here Code to validate SQL Scripts
Pretty straightforward to use though. If it returns null, then there were no errors in parsing it.
using Microsoft.Data.Schema.ScriptDom;
using Microsoft.Data.Schema.ScriptDom.Sql;
public class SqlParser
{
public List<string> Parse(string sql)
{
TSql100Parser parser = new TSql100Parser(false);
IScriptFragment fragment;
IList<ParseError> errors;
fragment = parser.Parse(new StringReader(sql), out errors);
if (errors != null && errors.Count > 0)
{
List<string> errorList = new List<string>();
foreach (var error in errors)
{
errorList.Add(error.Message);
}
return errorList;
}
return null;
}
}
Set your query to sql with this hint:
set PARSEONLY on
It just checks your query and returns, like this:
set PARSEONLY on
select * from tablea
Returns no exception.
While
set PARSEONLY on
select * f rom tablea
returns
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'f'.
If you would like to validate/parse just a SELECT statement, regardless of how "heavy-duty" that select statement is, I found out that the best and fastest way to validate a select statement is the following:
- in your code create 2 select statements (strings) such as:
1) Your valid select statement: SELECT * FROM HUGE_TABLE JOIN MULTIPLE_TABLES WHERE <<Condition>>
2) Create a similar select statement such as SELECT TOP 1 * FROM HUGE_TABLE JOIN MULTIPLE_TABLES WHERE <<Condition>>
- Parse/Validate just the second one, regardless of how many joins you have in there, it will parse it in milliseconds, such as:
SqlCommand sqlParse = new SqlCommand(ParseSelectStatement, sqlConn);
try
{
sqlConn.Open();
sqlParse.ExecuteNonQuery()
}
Hope it helps! Cheers!
I think this is what you are looking for. http://www.codeproject.com/KB/database/sqlvalidator.aspx

Dapper.net SQL Syntax Error with DynamicParameters

I'm trying to build a dynamic sql query to update a table in SQL Server, like this:
string alan = "SaticiKodu";
DynamicParameters paramStSabit = new DynamicParameters();
string sqlSabit = "UPTADE TBLSTSABIT SET ";
if (alan == "SaticiKodu")
{
sqlSabit += " SATICI_KODU = #SaticiKodu ,";
paramStSabit.Add("SaticiKodu", _msk.SaticiKodu);//_msk.SaticiKodu comes from List<T> in foreach loop
}
if (sqlSabit.Contains("=")) // here I check if I have any column update with '='
{
sqlSabit += "WHERE STOK_KODU = #StokKodu";
paramStSabit.Add("StokKodu", _msk.StokKodu);
sqlSabit= sqlSabit.Replace(",WHERE", " WHERE");
db.Execute(sqlSabit, paramStSabit, transaction: _transaction, commandType: CommandType.Text);
}
I have a list of objects, it has lots of properties but to make example short, here I write only StokKodu and StokAdi. This code throws an error
Incorrect syntax at '='
I think this code should work with Dapper.
How can I make this code work, where is my mistake? Thanks for the help from now.
All i do is changing
string sqlSabit
to
StringBuilder sqlSabit
and instead of join strings with +=, i used sqlSabit.Append(), now code is working. And i tested with string, integer and float typed columns/parameters, no problem.
But couldn't understand why StringBuilder solves the problem.

EF generates wrong query, causing exception: Must declare the scalar variable '#...'

I am using Entity Framework 4.3, and below is my code (BTW, the RealPrice field of the gift table is of decimal type):
var filters = new StringBuilder();
var parameters = new List<object>();
decimal numRealPrice = 25.00m;
filters.Append("RealPrice = #RealPrice");
var paramRealPrice = new SqlParameter("#RealPrice", SqlDbType.Decimal);
paramRealPrice.Value = numRealPrice;
parameters.Add(numRealPrice);
string sqlStatement = "SELECT * FROM gift WHERE ";
sqlStatement = sqlStatement + filters;
List<OM_Gift_BO> gifts = this.objEntity.ExecuteStoreQuery<OM_Gift_BO>(sqlStatement, parameters.ToArray()).ToList();
//....
And the framework somewhat generated a SQL query(according to Express profiler 2.0):
exec sp_executesql N'SELECT * FROM gift WHERE RealPrice = #RealPrice',N'#p0 decimal(4,2)',#p0=25.00
go
I have no idea where does the name 'p0' come from, however, since it is different from RealPrice, I got an exception saying:
Must declare the scalar variable "#RealPrice".
Well, this method works OK with string type parameters.
Any help is appreciated, thanks in advance.
The problem seems to be your assigning numRealPrice directly to your parameters and passing that directly to ExecuteStoreQuery
Replace
parameters.Add(numRealPrice);
With
parameters.Add(paramRealPrice);
Additionally I'm not sure if its of any value, as it depends on what your trying to achieve, however you could probably shorten your code as follows
var statement = "SELECT * FROM gift WHERE RealPrice = {0}";
var gifts = context.ExecuteStoreQuery<OM_Gift_BO>(statment, numRealPrice).ToList();

Query validation using C#

I am looking for a query validator in C#, which allows me to parse the SQL text from a textbox and verify whether it's correct or not before sending it for execution (MS SQL or DB2 queries).
If you want to validate SQL syntax without the use of a database, the TSql100Parser class will do well for this situation.
Disclaimer, code borrowed from this post here Code to validate SQL Scripts
Pretty straightforward to use though. If it returns null, then there were no errors in parsing it.
using Microsoft.Data.Schema.ScriptDom;
using Microsoft.Data.Schema.ScriptDom.Sql;
public class SqlParser
{
public List<string> Parse(string sql)
{
TSql100Parser parser = new TSql100Parser(false);
IScriptFragment fragment;
IList<ParseError> errors;
fragment = parser.Parse(new StringReader(sql), out errors);
if (errors != null && errors.Count > 0)
{
List<string> errorList = new List<string>();
foreach (var error in errors)
{
errorList.Add(error.Message);
}
return errorList;
}
return null;
}
}
Set your query to sql with this hint:
set PARSEONLY on
It just checks your query and returns, like this:
set PARSEONLY on
select * from tablea
Returns no exception.
While
set PARSEONLY on
select * f rom tablea
returns
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'f'.
If you would like to validate/parse just a SELECT statement, regardless of how "heavy-duty" that select statement is, I found out that the best and fastest way to validate a select statement is the following:
- in your code create 2 select statements (strings) such as:
1) Your valid select statement: SELECT * FROM HUGE_TABLE JOIN MULTIPLE_TABLES WHERE <<Condition>>
2) Create a similar select statement such as SELECT TOP 1 * FROM HUGE_TABLE JOIN MULTIPLE_TABLES WHERE <<Condition>>
- Parse/Validate just the second one, regardless of how many joins you have in there, it will parse it in milliseconds, such as:
SqlCommand sqlParse = new SqlCommand(ParseSelectStatement, sqlConn);
try
{
sqlConn.Open();
sqlParse.ExecuteNonQuery()
}
Hope it helps! Cheers!
I think this is what you are looking for. http://www.codeproject.com/KB/database/sqlvalidator.aspx

Categories

Resources