I got and SQL select syntax error - c#

I want to find the number of rows in the table data urunAd but I get an error like this
Syntax error (missing operator) in query expression 'urunAd='.
OleDbCommand komut = new OleDbCommand(
"SELECT COUNT(*) FROM Urunler WHERE urunAd= " + tbAd.Text + "", baglan);
and also - How do I present the results in my ASP.Net?

you are assigning text. You should add '' around the text:
OleDbCommand komut = new OleDbCommand(
"SELECT COUNT(*) FROM Urunler WHERE urunAd='" + tbAd.Text + "'", baglan);
but instead of doing so - use parameterized queries: (here is a short example)
using (OleDbCommand komut = new OleDbCommand("SELECT COUNT(*) FROM Urunler WHERE urunAd=#value", connection))
{
komut.CommandType = CommandType.Text;
komut.Parameters.AddWithValue("#value", tbAd.Text);
/* execute the query... */
}
For presenting the results in your ASP.Net a quick search on google along the line of "how to present result from sql command in asp.net" gave quite a few results. Among them

Related

How to use like operator with %?

I am creating a search bar and I am having a hard time constructing the correct query for that. Here is my code:
SqlCommand command1 = new SqlCommand(
"Select * from tbl_customer where customer_name like '%''"+ textBox1.Text +"''%' ",
MySqlConnection);
SqlCommand command1 = new SqlCommand("Select * from tbl_customer where customer_name like #search_value", MySqlConnection);
command1.Parameters.AddWithValue("#search_value","%" + textBox1.Text + "%");
You are adding too many 's.
SqlCommand command1 = new SqlCommand(
"Select * from tbl_customer where customer_name like '%"+ textBox1.Text +"%' ",
MySqlConnection);
Note that I have removed the extra 's after the first % and before the last %.
However, you should be careful about SQL injection and use parameters instead of directly adding control values into your query.
SqlCommand command1 = new SqlCommand(
"Select * from table-name where column-name like '%"+ textboxid.Text +"%' ",
MySqlConnection);
If u making a sample program then ok it will work ,but if you are looking for a professional use software or website then don't go with this method . Check sql injection because here you are directly adding the control values in query

How can I get values from database

I tried to get values from access data base with two where clause. This is the error that I got!
"Syntax error (missing operator) in query expression 'unit1<=34 and unit2>=34 where"'.
and this is my code:
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\Work\\Office\\Electricity_Board_bill_calculator\\gk.accdb;");
con.Open();
OleDbCommand com5 = new OleDbCommand("select id from tblBillConfig where unit1<="
+ contot + " and unit2>=" + contot + " where group=3 ", con);
You have 'where' in 2 places of the SQL string. This is at least one reason for the error.
There are a couple of potential issues:
You can't have 2 where clauses. The second filter needs to be introduced with and`
Group is a reserved keyword, so and needs to be escaped. (This would be [group] in Sql Server. I'm not sure how to do this in MS Access)
You should also look at using parameters to bind variables. This addresses a bunch of issues, such as sql injection, and also improves performance as the parameterization may allow your RDBMS to cache the query plan.
So your query should look something like this:
var com5 = new OleDbCommand("select id from tblBillConfig " +
" where unit1<=? and unit2>= ? and [group]=3 ", con);
command.Parameters.Add("#p1", OleDbType.Integer).Value = 34;
command.Parameters.Add("#p2", OleDbType.Integer).Value = 34;

like statement for npgsql using parameter

I have a postgresql DB and i want to query the table "Locations" to retrieve the names of all the locations that match the name that's entered by the user. The column name is "LocationName". I'm using ASP.net with C#.
NpgsqlConnection con = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString());
NpgsqlCommand cmd = new NpgsqlCommand("Select * from \"Locations\" where \"LocationName\" LIKE \"%#loc_name%\"", con);
cmd.Parameters.AddWithValue("#loc_name", Location_Name);
NpgsqlDataReader reader = cmd.ExecuteReader();
I get this exception:
Npgsql.NpgsqlException: ERROR: 42703: column "%((E'My place'))%" does not exist
I've tried running the query without using %, but it doesn't work.
I've also tried using + and & like given below but that didn't work either:
string query = "Select \"LocationName\" from \"Locations\" where \"LocationName\" LIKE '%'+ :loc_name +'%'";
with the above line, i get this exception:
Npgsql.NpgsqlException: ERROR: 42725: operator is not unique: unknown + unknown
you should use
NpgsqlCommand cmd = new NpgsqlCommand("Select * from \"Locations\" where \"LocationName\" LIKE #loc_name", con);
cmd.Parameters.AddWithValue("#loc_name", "%" + Location_Name + "%");
you were inserting too much quotes: Postgre interpretes the string between double quote as a field/table-name. Let the parameter do the escape-string job
P.S.: To concatenate string in Postgre you should use the || operator, see here. So your last query should be
string query = "Select \"LocationName\" from \"Locations\" where \"LocationName\" LIKE '%' || :loc_name || '%'";

SQL Select statement from a webpage control and check relevant check boxes according to result

I have a sql select statement in my VS2005 C# server-side coding for a web application and I am meeting some errors.
Below is a screenshot of the controls in the webpage:
Data Source SqlDataSource1 : Query:SELECT [Name] FROM [Users].
Dropdownlist UserNameList : Lists all userName retrieved from SqlDataSource1.
Checkboxes AdminCb and UserCb : Automatically checks if the userType of the userName is as.
Button loadUser : Gets the user type and checks the check boxes accordingly.
Below is my code for my loadUser button
SqlConnection conn = new SqlConnection("Data Source=DATASOURCE");
string sql = string.Format("SELECT [User Type] FROM [Users] where Name like " + UserNameList.Text);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
if(sql== "Administrator"){
AdminCb.Checked=true;
}
if(sql== "User"){
UserCb.Checked=true;
}
Currently I am stuck with the error (Wong is the 2nd word of the user's name):
Questions:
1) How can change my Sql query so that it can take in more than 1word?
2) And will I be able to check boxes once I am able to run my sql query?
Thank You.
You must have to use Parameter and call the ExecuteScalar() method instead of ExecuteNonQuery().
string sql = "SELECT [User Type] FROM [Users] where [Name]=#Name";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name",SqlDbType.VarChar,50).Value=UserNameList.Text;
conn.Open();
Object result=cmd.ExecuteScalar();
conn.Close();
if(result!=null)
{
string usertype=result.ToString();
if(usertype=="Administrator")
{}
else
{}
}
In case, if result returned from the database contains more then one rows then use ExecuteReader() method.
string sql = "SELECT [User Type] FROM [Users] where [Name] like #Name";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name",SqlDbType.VarChar,50).Value="%" + UserNameList.Text + "%";
conn.Open();
SqlDataReader result=cmd.ExecuteReader();
while(result.Read())
{
///
}
result.Close();
conn.Close();
Since you are concatenating the SQL string, if the input itself has a single quote in it, it thinks this is the end of the input, and the continuing input is SQL statements, which is why you may be getting that error.
Switch to using a parameter, or make sure any single quotes are escaped as a pair of single quotes, like:
string sql = string.Format("SELECT [User Type] FROM [Users] where Name like " + UserNameList.Text.Replace("'", "''"));
Since the error is indicating there is something wrong with the Name, I would take a closer look at this line:
string sql = string.Format("SELECT [User Type] FROM [Users] where Name like " + UserNameList.Text);
If you are using string.Format, you might as well use it
string sql = string.Format("SELECT [User Type] FROM [USERS] where Name like {0}", UserNameList.Text);

Help me Fix this SQL Statement?

Can someone let me know what is wrong with my SQL Statement and how I can improve it?
da = new SqlDataAdapter("SELECT * FROM Guests"+" WHERE Students.name='" +
byNametextBox.Text + "'", MyConn);
An EXISTS predicate is slightly more efficient than a JOIN if you want only columns from one of the tables. Additionaly - never inject strings into SQL statements like that - you're just begging for SQL Injection attacks, or related crashes errors (Yes, I know it's a Forms application, but the same holds true. If you're searching for a name like "O'Leary", you'll get a crash).
SqlCommand cmd = new SqlCommand("SELECT * FROM Guests WHERE EXISTS (SELECT Id FROM Students WHERE Guests.StudentId = Students.Id And Students.name= #name)", MyConn);
cmd.Parameters.Add("#name", SqlDbType.VarChar, 50).Value = byNametextBox.Text;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
Note: Some people may argue that "SELECT *" is bad, and that you should consider specifying individual column names
You need to worry about SQL Injection. Put simply, SQL Injection is when a user is able to put arbitrary SQL statements into your query. To get around this, either use a Stored Procedure or a Parametrized SQL Query. An Example of a Parametrized SQL query is below:
SqlConnection conn = null;
SqlDataReader reader = null;
//Connection string goes here
string studentName = byNametextBox.Text;
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Guests "+" WHERE Students.name = #name", conn);
SqlParameter param = new SqlParameter("#name", SqlDbType.NVarChar, 50);
param.Value = studentName;
cmd.Parameters.Add(param);
reader = cmd.ExecuteReader();
//Do stuff with reader here
SqlDataAdapter("SELECT Guests.* FROM Guests,Students WHERE Guest.StudentId = Student.Id and Students.name='" + byNametextBox.Text + "'", MyConn);`
You need an Inner Join. I think it would be something like this:
SELECT Guests.* FROM Guests INNER JOIN Students ON Students.name = Guests.name WHERE Students.name = '" + byNametextBox.Text + "'"
Try it:
"SELECT g.*
FROM Guests g
INNER JOIN Students s ON g.StudentId = s.StudentId
WHERE Students.Name = '" + byNametextBox.Text + '"'
Assuming that the field wich relates both tables is StudentId.
Beware that SQL is not the same between different Servers. This statement will work on Sql Server, I don't know in others. Also, beware that you aren't protecting yourself on SQL Injection attacks. You should perform your query with parameters, instead of concatenating strings in the way you are doing it.
This is a simple query that you should know by yourself. You can search for tutorials on Google, but here is a generic introduction.

Categories

Resources