I am using select statement to retrieve certain data from sqlite. The result contains ' char which results error when selecting data. How can I ignore it?
Below is my sql statement:
string query = string.Format("select * from TableA where [Col]='{0}'",suraTName)
Statement: select * from TableA where [Col]='An-Naazi'aat'
How to ignore ' char and have the correct the result?
Thanks!
You should use a parameterized query like this
string query = "select * from TableA where [Col]=#colValue";
SQLiteCommand cmd = new SQLiteCommand(query, con);
cmd.Parameters.AddWithValue("#colValue", suraTName);
In this way the job to correctly quote your value is passed to the SQLite provider that knows better. Also, there is no possibility of Sql Injections
Of course this is possible if you are using a ADO.NET provider like the one from System.Data.SQLite, if you are using other systems to retrieve your data, I can only suggest to double the single quote in your query
suraTName = suraTName.Replace("'", "''");
string query = string.Format("select * from TableA where [Col]='{0}'",suraTName);
But it is very risky option
Related
I am executing this query in SQLite for .NET
string SQL = "SELECT * FROM EmployeeStats where TransactionDateTime = '$date'";
using (SQLiteCommand command = new SQLiteCommand(SQL, DbConnection as SQLiteConnection))
{
command.Parameters.AddWithValue("$date", DateTime.Now.ToString(DateFormatterString));
SQLiteDataReader reader = command.ExecuteReader();
string query = command.CommandText;
foreach (SQLiteParameter p in command.Parameters)
{
query = query.Replace(p.ParameterName, p.Value.ToString());
}
}
The reader returns zero rows.
I am generating the sql query using the foreach loop. If i execute the query generated by this loop manually in the database then it returns the correct rows.
Currently the Database column for the dates is set to TEXT. However i have also tried DATE and TIMESTAMP and changed the parameter addition to this. But still the same problem:
command.Parameters.Add("$date", DbType.DateTime).Value = DateTime.Now.ToString(DateFormatterString);
See this images showing it working fine when executed manually.
EDIT. I simplified the example.
SELECT * FROM EmployeeStats where TransactionDateTime = '$date'
should be
SELECT * FROM EmployeeStats where TransactionDateTime = $date
or #date, or :date, depending on the SQL variant; worst case, it could also be
SELECT * FROM EmployeeStats where TransactionDateTime = ?
if named parameters aren't a "thing" on that provider.
'$date' is the string literal consisting of 5 characters: $, d, a, t, e - not the value of the parameter called date
This is my sql
var maxLimit =100;
var sql = "Select Top #MaxLimit from Table WHere data =#Id"
conn.Query<Result>(sql, new {
Id = customerId,
MaxLimit = maxLimit
})
But I get a system error
incorrect syntax near #MaxLimit.
Is Dapper not able to parametrize fields like Top, or Fetch?
In SQL Server any top expression other than a numeric constant needs to be in parentheses.
SELECT TOP (#MaxLimit) FROM ...
Newer versions of dapper have literal replacements and they work great in this case:
var sql = "Select Top {=MaxLimit} from Table WHere data = #Id";
There must be some very obvious answer but i just can not see it nor find solution from web.
I try to count from db table how many rows contains file path LIKE "path".
In Access Settings-table I have rows where path field (short text type) containing string:
\\server\dir\something\
I want to count the rows where field begins with "\server\dir..".
After failing this with MS Access I started testing with mariaDB & heidiSQL and had some trial and error before getting valid answer with this query:
SELECT COUNT(*) FROM `Settings` WHERE `path` LIKE "%\\\\\\\\server\\\\dir\\\\%"
-> returns Count(*) = 3
In C# i get same return with this (found again with trial and error):
string query = #"SELECT COUNT(*) FROM Settings WHERE path LIKE '%\\\\\\\\server\\\\dir\\\\%'";
var Test = MySqlHelper.ExecuteScalar(connString, query);
-> returns Count(*) = 3
Now I cant get the same work with C# and Access using OleDb library:
string query = #"SELECT COUNT(*) FROM Settings WHERE path LIKE '*\\\\\\\\server\\\\dir\\\\*'";
OleDbConnection connection = new OleDbConnection(databsefile);
OleDbCommand command = new OleDbCommand(query, connection);
connection.Open();
var Test = command.ExecuteScalar();
-> returns Count(*) = 0
I have also tried queries (with C# and Access using OleDb library):
string query = #"SELECT COUNT(*) FROM Settings WHERE path LIKE '*\\\\server\\dir\\*'";
-> return count(*) = 0
string query = #"SELECT COUNT(*) FROM Settings WHERE path LIKE '*\\server\dir\*'";
-> return count(*) = 0
This works in MS Access 2013 giving valid result:
SELECT COUNT(*) FROM Settings WHERE path LIKE '*\\server\dir\*'
->returns Count(*) = 3
EDIT: Changed db table name table -> Settings
When you use the # before the string, you do not need to escape the backslashes again. And the placeholder for LIKEs is %, not *.
So try:
string query = #"SELECT COUNT(*) FROM table WHERE path LIKE '%\\\\server\\dir\\%'";
To avoid all that escaping though, consider using SQL parameters.
PS: table is a reserved keyword. You should not name a table table, this will always cause issues.
You reported this query works correctly in Access:
SELECT COUNT(*) FROM table WHERE path LIKE '*\server\dir*'
With your c# code, you are using OleDB to interface with the Access database. And OleDb requires ANSI wildcards: % and _ instead of * and ?.
So, since the above query worked inside Access, this one should work from c#:
SELECT COUNT(*) FROM [table] WHERE path LIKE '%\server\dir%'
Queries run with OleDb also seem to be more vulnerable to trouble with reserved words. So I enclosed table in square brackets to avoid trouble.
If you want a query which will always work the same inside or outside of Access, use ALike instead of Like. ALike signals the database engine to expect ANSI wild cards:
SELECT COUNT(*) FROM [table] WHERE path ALIKE '%\server\dir%'
So Ms Access use * as a wildcard like T_D indicated and which is what my valide query use in MS Access. BUT like HansUp indicated C# OleDb API still uses ANSI wild cards.
But small correction even to that answer would be to escape the query in c#. So query returning valid answer is:
string query = "SELECT COUNT(*) FROM Settings WHERE path LIKE '%\\\\server\\dir\\%'";
OR
string query = #"SELECT COUNT(*) FROM Settings WHERE path LIKE '%\\server\dir\%'";
-> returns Count(*) = 3
HansUp also pointed that using ALIKE instead of LIKE % also works in MS Access so that way query is compatible with ANSI wildcard %
So here is my working solution (with command parameters):
string destFolder = #"\\server\\dir\";
string query = "SELECT COUNT(*) FROM Settings WHERE path LIKE #destFolder;";
using (OleDbConnection connection = new OleDbConnection(mdbfile))
{
using (OleDbCommand command = new OleDbCommand(query, connection))
{
command.Parameters.AddWithValue("#destFolder", "%" + destFolder + "%");
try
{
connection.Open();
if ((int)command.ExecuteScalar() == 3)
{
return true;
}
else
{
return false;
}
}
catch (OleDbException ex)
{
//handle OleDb error
return false;
}
}
}
I'm trying to understand why in C# if you have a sql string why you would have to put tick (') marks in the following where clause in order for this to work. Could someone please explain the reasoning behind this?
where ProgramServer='" + machineName.ToString() + "' and Active=1;
You can avoid those tick (') marks and use Parameters, They will also save you from SQL Injection.
The reason you see those ticks are because SQL expects string type values to be enclosed in single ticks.
What you're seeing is a dynamically built SQL query in the code. When querying based on a string value, the string must be wrapped in single quotes. The final SQL string would look something like:
select * from someTable where ProgramServer = 'YourMachineName' and Active = 1;
Unfortunately, that is far from the best way to do things. You should be using parameterized queries instead:
var query = "select * from someTable where ProgramServer = #machineName and Active = 1;";
using(var conn = new SqlConnection(connString))
{
var command = new SqlCommand(query, conn);
command.Parameters.Add("machineName", machineName.ToString());
// Execute and get the results
}
I am new to .net/C#. Coming from PHP and some Java, I am finding the new languages interesting and challenging.
I have an issue with a sql string
string query = #"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = '"+querystring + "' ORDER BY lname ASC";
Which to me, looks fine. however when run my solution and output the query as it is not working, I get this as my output:
select * from Users where role='member' and SUBSTRinG(lname, 1, 1)
= ' O ' ORDER BY lname ASC
This is output into my Firebug console (the page that uses this query is accessed via AJAX).
Is their a reason my 's are being turned into their code version, ie '''
Thanks
In C# you should be using SqlCommand to excute the query, and to prevent sql injection using the parameter collection.
Your query seems fine - The issue might be the way you are running it or the parameters being supplied. Update your question with more details on what you are expecting vs what is happening, include any error messages generated.
Below is a general guideline of how to get data from a sql table to a c# Data Table object.
SqlConnection conn = new SqlConnection("YourConnectionString");
SqlCommand cmd = new SqlCommand(#"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = #query ORDER BY lname ASC");
cmd.Parameters.AddWithValue("#query", querystring);
DataTable resultTable = new DataTable();
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(resultTable);
} finally {
if (conn.State != ConnectionState.Closed) conn.Close();
}
Console.WriteLine(String.Format("Matched {0} Rows.", resultTable.Rows.Count));
For SQL injection protection:
You can provide escape sequence for single quotes by replacing them with two single quotes '' so that it will be treated as a single quote inside SQL strings. Otherwise it is considered as a start or end of the string value in SQL.
Replacing single quotes using ' in .net is also preferred but its better going with two single quotes.