SQL limit error - c#

I use this code in my project (SQL COMPACT):
"select Name
from Drug
where Name
like '" + Dname + "%'
limit 10"
Dname is a string value. The result is this error:
There was an error parsing the query.
[ Token line number = 1,Token line offset = 44,Token in error = LIMIT ]
Why is this happening and how can I fix it?

i think what you want is
"select TOP (10)
from Drug
where Name
like '" + Dname + "%' "
you should also try using parametrized queries:
string qry = "select TOP(10) from Drugs where name like #dname";
SqlCommand oCmd = new SqlCommand(qry, ConnectionString);
oCmd.Parameters.AddWithValue("#dname", dname + '%');

Never use string concatenations to build SQL queries. Always use parametrized queries:
string connectionString = ....
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT TOP 10 FROM drug WHERE name LIKE #name";
cmd.Parameters.AddWithValue("#name", Dname + '%');
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
...
}
}
}

According to this previous question, the proper syntax is TOP(n), so try this:
"select TOP(10) Name
from Drug
where Name
like '" + Dname + "%' "

Related

How to insert in c# using custom table name

This is partial code which i try
SqlConnection con = new SqlConnection(#"Data Source=ANSARI-PC\;Initial Catalog=BMS;Integrated Security=True");
string tname = idc + "-InvoiceT";
string sql = "select count(*) from '"+ tname + "' ";
con.Open();
SqlCommand sda = new SqlCommand(sql, con);
SqlDataReader myreader;
myreader = sda.ExecuteReader();
int lid;
For above code im getting this error Incorrect syntax near '2-InvoiceT'
2-InvoiceT is table name in database 'idc' contain 2 as value.
Change
string sql = "select count(*) from '"+ tname + "' ";
to
string sql = "select count(*) from ["+ tname + "] ";

How to use wildcards in SQL query with parameters

Say I have a basic query, something like this:
SELECT holiday_name
FROM holiday
WHERE holiday_name LIKE %Hallow%
This executes fine in my sql query pane and returns 'Halloween'. My problem occurs when I try to use parameters with with the wildcard '%' characters in my code.
SqlConnection Connection = null;
SqlCommand Command = null;
string ConnectionString = ConfigurationManager.ConnectionStrings["SQLdb"].ConnectionString;
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE %#name%";
Connection = new SqlConnection(ConnectionString);
try
{
Connection.Open();
Command = new SqlCommand(CommandText, Connection);
Command.Parameters.Add(new SqlParameter("name", HolidayTextBox.Text));
var results = Command.ExecuteScalar();
}
catch (Exception ex)
{
//error stuff here
}
finally
{
Command.Dispose();
Connection.Close();
}
This throws an incorrect syntax error. I've tried moving the '%' to my parameter like so
Command.Parameters.Add(new SqlParameter("%name%", HolidayTextBox.Text));
but then I receive an error saying I haven't declared the scalar variable '#name'. So, how do you properly format wildcard characters to be included with query parameters? Any help is appreciated!
First off, your SqlParameter name is #name not name.
Second, I would move your wildcards.
So it would look like this:
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE #name;"
Connection = new SqlConnection(ConnectionString);
try
{
var escapedForLike = HolidatyTextBox.Text; // see note below how to construct
string searchTerm = string.Format("%{0}%", escapedForLike);
Connection.Open();
Command = new SqlCommand(CommandText, Connection);
Command.Parameters.Add(new SqlParameter("#name", searchTerm));
var results = Command.ExecuteScalar();
}
Note that LIKE requires special care when passing parameters and you need to escape some characters Escaping special characters in a SQL LIKE statement using sql parameters.
whatever you do don't do this:
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE '%'" + HolidayTextBox.Text + "'%'";
as that will open you up to sql injection, instead do this:
Command.Parameters.Add(new SqlParameter("#name", "%" + HolidayTextBox.Text + "%"));
you may like to know about Command.Parameters.AddWithValue, e.g:
Command.Parameters.AddWithValue("#name", "%" + HolidayTextBox.Text + "%");
The %s should be part of the search string, not the query.
string CommandText = "SELECT holiday_name "
+ "FROM holiday "
+ "WHERE holiday_name LIKE #name";
Connection = new SqlConnection(ConnectionString);
try
{
Connection.Open();
Command = new SqlCommand(CommandText, Connection);
string name = "%" + HolidayTextBox.Text + "%";
Command.Parameters.Add(new SqlParameter("#name", name));

selecting data between 2 dates

I am Working in ASP.NET and SqlServer.
I have two textboxes with calender extender in my application where user will select two dates.I want to get data between those two dates from sqlserver where my datatype for that particular field is DateTime. please tell me how to proceed with this ...I wrote a query but thats not working..
my query:
SqlCommand cmd = new SqlCommand("select top 1 OrderNumber from tblOrderMaster where OrderedDate>='" + txtfromcal.Text + "' and OrderedDate<='" + txttocal.Text + "' ", conn);
things to do
parameterized the query to prevent from sql injection
use using statement to properly dispose the object
use try-catch block to handle excpetion
eg,
string query = #"select top 1 OrderNumber
from tblOrderMaster
where OrderedDate BETWEEN #startDate AND #endDate";
using(SqlConnection conn = new SqlConnection("connectionString here"))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#startDate", txtfromcal.Text);
cmd.Parameters.AddWithValue("#endDate", txttocal.Text);
try
{
conn.Open();
// other codes
// to fetch the record
}
catch(SqlException e)
{
// do something with
// e.ToString()
}
}
}
SOURCES
AddWithValue Method
Add (recommended method to be used)
use this code:
Sqlcommand cmd=new sql command ("Select data from tablename
where date>=startdate
and date<=enddate",connection)
Try this
SELECT * FROM YourTableName WHERE sqlDateColumnName BETWEEN '" + textbox1.Text + "' AND '" + textbox2.Text + "'

Parameterize a SELECT ROWCOUNT sql statement

I am using VS2005 C# and SQL Server 2005.
I have a a few SQL queries which I am converting them from using parameters instead concatenations for SQL injection prevention.
Below is a SELECT query which is parameter-ed:
string loggedinuser = (User.Identity.Name);
SqlDataSource1.SelectCommand = "SELECT * FROM [UserTable] where [" + DropDownList1.Text + "] like #searchtb AND [LoggedInUser] LIKE #userlog";
SqlDataSource1.SelectParameters.Add("searchtb", "%" + searchTB.Text + "%");
SqlDataSource1.SelectParameters.Add("userlog", "%" + loggedinuser+ "%");
The above sql query searches for records base on the user's input in a search textbox and return results which matches the search input and username in the database.
I have another SQL query which is also a SELECT statement. However, this time it does not use SqlDataSource, but using cmd instead. Thus I need some help in converting the SQL statement below to parameter form:
string loggedinuser = (User.Identity.Name);
string stmt = "SET ROWCOUNT 1 SELECT COUNT(*) FROM MP.dbo.UserTable where [" + DropDownList1.Text + "] like '%" + searchTB.Text + "%' AND [LoggedInUser] LIKE '%"+loggedinuser +"%'";
int count = 0;
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
thisConnection.Close();
}
This SQL query searches for number of records that the user is trying to search base on his search input and username. And if countuser returns a 0 value, I will prompt the user after that.
I need help in converting the 2nd SQL statement into parameter form.
Thank you.
Try,
string stmt = "SELECT COUNT(*) FROM MP.dbo.UserTable where [" + DropDownList1.Text + "]
like #searchTb AND [LoggedInUser] LIKE #loggedinuser";
int count = 0;
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
cmdCount.Parameters.Add("#searchTb",SqlDbType.VarChar,40).Value="%" + searchTB.Text + "%";
cmdCount.Parameters.Add("#loggedinuser",SqlDbType.VarChar,40).Value="%" + loggedinuser + "%";
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
thisConnection.Close();
}
Using stored procedures is your best bet, but if you cannot use them, this code should work:
SqlDataAdapter myCommand = new SqlDataAdapter(
"SELECT au_lname, au_fname FROM Authors WHERE au_id = #au_id", conn);
SQLParameter parm = myCommand.SelectCommand.Parameters.Add("#au_id",
SqlDbType.VarChar, 11);
Parm.Value = Login.Text;
This is from the MSDN article on SQL injection.
http://msdn.microsoft.com/en-us/library/ms161953.aspx

Getting Data from Access into a text box in C# by clicking a button

I have a table in MS Access that contain: (FoodID, FoodName, Price).
In C# I have three text boxes (txtId, txtName, txtPrice) and a button (btnSearch).
My question is that, In C# I just type FoodID in (txtId) and then click on button Search It'll display FoodName and Price ( from table access) in txtName and txtPrice by itself. I got the source code from you but it error on (OleDbDataReader dr = cmd.ExecuteReader();) its message is "Data type mismatch in criteria expression" .
Please solve this problem for me. This is the whole source code that I got for you.
System.Data.OleDb.OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "your connection string";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();//error this line!
while(dr.Read())
{
txtName.Text = dr["FoodName"].ToString();
txtPrice.Text = dr["Price"].ToString();
}
dr.Close();
conn.Close();
I assume FoodID is int. You should remove single quotes in this case
cmd.CommandText = "select FoodName, Price from tablename where FoodID = " + txtId;
Even better - use parameters:
using (var connection = new OleDbConnection("your connection string"))
using (var command = connection.CreateCommand())
{
command.CommandText = "select FoodName, Price from tablename where FoodID = #FoodID";
command.Parameters.AddWithValue("FoodID", int.Parse(txtId.Text));
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
txtName.Text = reader["FoodName"].ToString();
txtPrice.Text = reader["Price"].ToString();
}
}
I think the FoodId is of Integer type in the database but over here in the query you have passed as string so convert the string to integer.
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + int.Parse(txtId.Text) + "' " ;
There seems to be no problem with this line of code :
OleDbDataReader dr = cmd.ExecuteReader();// correct way
I think the problem is in:
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
You need to use the .Text Propertie of the Textbox
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId.Text + "' ";

Categories

Resources