Dapper Parameter replace not working for Top - c#

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";

Related

Incorrect syntax near the keyword 'Order' - Order is table name

List<Order> results = new List<Order>();
db.Cmd = db.Conn.CreateCommand();
db.Cmd.CommandText = "SELECT * FROM Order";
db.Rdr = db.Cmd.ExecuteReader();
while (db.Rdr.Read())
{
results.Add(getOrderFromReader(db.Rdr));
}
db.Rdr.Close();
return results;
I get this error when this code runs
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Order'.'
The result is a list of Order objects. The name of the table is Order exactly. The method getOrderFromReader just takes a row of data from the order table and in puts it into a new order object. I have used this format of code to extract data from all of the tables in the database and the rest works fine but its just the Order table that I get this error for, I don't know if this is because of other settings in the database.
You will need to put the name of the table in square brackets in order for it to work.
List<Order> results = new List<Order>();
db.Cmd = db.Conn.CreateCommand();
db.Cmd.CommandText = "SELECT * FROM [Order]";
db.Rdr = db.Cmd.ExecuteReader();
while (db.Rdr.Read())
{
results.Add(getOrderFromReader(db.Rdr));
}
db.Rdr.Close();
return results;
Order is a SQL reserved word, so you might think about renaming that table, if you can.
Order is a keyword in SQL used for Ordering/sorting of the resultset.
Here the complier is getting confused with the keyword and your table name.
Solutions :
Rename your table name
Enclose your table name in brackets. [Order]. ie,
Select * From [Order]

razor and cshtml: how to db.Execute for select statement?

I am doing a quick CSHTML page for the purpose of testing.
I need to access database based on the id parameter on the URL:
var id = Request.QueryString["id"];
var db = Database.Open("mydatabase_connection");
var query = "select * from myrecord where id = " + id;
var row = db.QuerySingle(query);
//i am able to display the field (called name) of the selected record in the following way:
#row.name
Obviously, the above approach is subject to security attack. I am hoping to retrieve the record the following way:
var query = "select * from myrecord where id=#0";
var row = db.Execute(query, id);
However, I get runtime error when retrieving the field value:
#row.name
What is the correct way of getting the "row" in the second approach?
Thanks and regards.
Database.Execute is for executing a non-query SQL statement and returns the count of records affected by the SQL statement as an Int.
I think the method you want to use really is Database.QuerySingle, which returns an Object.
ie.
var query = "select * from myrecord where id=#0";
var row = db.QuerySingle(query, id);
Razor:
#row.name
As far as safety from SQL injection goes, this approach is safe. You are passing the URL value into your query as a parameter.
The unsafe way to run the query would be with string concatenation:
var query = "select * from myrecord where id=" + id;
Don't do this! It allows for a malicious user to append SQL statements to your query! Always use parameterized queries instead.

SQL Syntax in C#

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
}

How to retrieve sql results containing ' char

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

C# Dapper query using WHERE IN

I am trying to perform a dapper query like this:
string query = "select * from MyTable where someNumber in #Nums;";
...
connection.Query<ReturnObj>(query, new {Nums = nums})
And I am getting a MySql syntax error if nums is empty. It looks like Dapper changes the query to look like this: WHERE 1 = 0) so I am guessing it the left ( is missing, which is causing the syntax error. Yes, I realize I could just check if the collection is empty before executing the query, but I would rather not if I don't have to.
This is a bug in Dapper where it creates a SQL statement that is invalid for MySQL Server 5.6 (and earlier).
Workarounds:
Upgrade to MySQL Server 5.7 (which accepts the SQL Dapper generates and returns the expected results)
As you said, check if the collection is empty before executing the query
A variant of checking if the collection is empty (that can be useful if you have a complex query, NOT IN, etc.):
var numsSql = nums.Any() ? "#Nums" : "(select null)";
var query = $"select * from MyTable where someNumber in {numsSql};";
conn.Query(query, new { Nums });

Categories

Resources