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 || '%'";
Related
I am working in C# using oraOleDb.oracle provider to query from a table. I have a question regarding using '?' in my SQL string where a BETWEEN keyword is used. My problem is how do I add 2 parameters for a single field?
string strSQL = "SELECT DISTINCT PRODUCT_LINE, MODEL_YEAR, ORDER_DATE "
+ "FROM ORDER_BANK "
+ "WHERE ((PRODUCT_LINE = ?) AND (MODEL_YEAR = ?) AND (ORDER_DATE BETWEEN ? AND ?))";
Command = new OleDbCommand(strSQL, Connection);
Command.Parameters.AddWithValue("PRODUCT_LINE", strprodline);
Command.Parameters.AddWithValue("MODEL_YEAR", strModelYear);
// ??? WHAT DO I DO HERE FOR "(ORDER_DATE BETWEEN ? AND ?)"
Why do you don't do this simpler, like bulding the sql string directly. for example:
var sql = $"select * from table where table.date1 between '{date1.toShortDateString()}' and {date2.toShortDateString()} and model_year = '{strModelYear}' and ....;";
Command = new OleDbCommand(sql, Connection);
C# >= 6.0 allows you to use "$" before a string and that means that all between { and } will executable code.
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
I am inserting data to a data list in asp.net. I need to modify the Select Command according to my needs. I did something like this,
string query = "SELECT [movieName], [sDate], [eDate], [IMDb], [imageUrl] FROM [movieDrama] WHERE ([category]='Drama' AND [movieName] like '%#key%') ORDER BY [movieName]";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#key", key);
SqlDataSource1.SelectCommand = query;
But this is not working. I think I did something wrong when defining '#key'. How to do it in correct way? Thanks in advance...
Use it like;
LIKE '%' + #key + '%'
instead of
LIKE '%#key%'
For full query;
string query = "SELECT [movieName], [sDate], [eDate], [IMDb], [imageUrl] FROM [movieDrama] WHERE ([category]='Drama' AND [movieName] LIKE '%' + #key + '%') ORDER BY [movieName]";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#key", key);
And actually, you don't need square brackets every column of your query, you just need to use when you want use some reserved keywords as a column names.
Just this:
string query = "SELECT [movieName], [sDate], [eDate], [IMDb], [imageUrl] FROM [movieDrama] WHERE ([category]='Drama' AND [movieName] like #key) ORDER BY [movieName]";
then
cmd.Parameters.AddWithValue("#key", "%"+ key + "%");
Try giving your sqlCommand the connection parameter:
SqlCommand cmd = new SqlCommand(query,YOURCONNECTIONSTRING);
cmd.Parameters.AddWithValue("key", key)
I'm having an issue with an error written above and cannot find a exact way to fix it.
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("Select count(*) from [contractors$] where " + category + " like '*#name*'", eh.Connection);
dataAdapter.SelectCommand.Parameters.Add("#name", OleDbType.VarChar).Value = "*" + name + "*";
OleDbCommand command = dataAdapter.SelectCommand;
OleDbDataReader reader = command.ExecuteReader();
The exact error is..
Syntax error (missing operator) in query expression 'like '#name''.
I've also already looked for solutions to this problem and have attempted to adapt them to try to get this work work, but with no luck(the one above was one of the attempts)
Much thanks in advance!
Ok, so I have now change the code to this..
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("Select count(*) from `contractors$` where " + category + " LIKE #name", eh.Connection);
dataAdapter.SelectCommand.Parameters.Add("#name", OleDbType.VarChar).Value = "%" + name + "%";
OleDbCommand command = dataAdapter.SelectCommand;
OleDbDataReader reader = command.ExecuteReader();
But I am still getting the same error.
A parameter cannot be contained inside an SQL string literal. Use concatenation to build the string:
"... LIKE ('%' + #name + '%') ..."
Update
It seems that the value of category was null or empty, creating an invalid SQL statement:
Select count(*) from [contractors$] where like '#name'
^^^ no category here
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);