Passing parameter in select statement in postgresql - c#

I am trying to pass parameter for below select statement in postgresql, but it is not returning any row,
cmd.Parameters.AddWithValue("#name", richTextBox_searchEmp.Text);
string sql = "select * from tbl_emp_Info where LOWER(firstname) like LOWER('#name%');";
where- richTextBox_searchEmp.Text is “first”
have also tried -
cmd.Parameters.AddWithValue("#name", NpgsqlDbType.Char , searchEmp.Text);
while, parameter less query below always returning correct results.
string sql = "select * from tbl_emp_Info where LOWER(firstname) like LOWER('first%');";
Please help!!!
Complete Code-
conn.Open();
cmd.Parameters.AddWithValue("#name", NpgsqlDbType.Char , richTextBox_searchEmp.Text);
string sql = "select * from tbl_emp_Info where LOWER(firstname) like LOWER('#name%');";
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
dataGridView.DataSource = dt;

Pass your parameter with % like
Change you query to
string sql = "select * from tbl_emp_Info where LOWER(firstname) like LOWER(#name);";
And Pass #name like
cmd.Parameters.AddWithValue("#name", "%" + searchEmp.Text + "%");

Related

get a parameter from database with query c#

string s = "select idviagem from tbviagem where dia like '" + idatxt.Text + "'";
cmd = new SqlCommand(s, con);
I need the idviagem from the table tbviagem to put in idviagem from tbpassageiro (it's FK on tbpassageiro) , but i need the get idviagem from idatxt.Text it's a DateTime format, but doing the insert (look down) gives me the error:
Conversion failed when converting the nvarchar value 'select idviagem from tbviagem where dia like '06/12/2018 00:00:00'' to data type int.'
but idviagem is a int, of course .
string q = "insert into tbpassageiro (nome,cc,fotocc,idviagem) values(#n,#cc,#p,#iv)";
cmd = new SqlCommand(q, con);
con.Open();
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.AddWithValue("#iv", s);
cmd.ExecuteNonQuery();
You should never execute SQL statements like that but use parameters. You are using parameters for your second statement but not doing it for the first one.
Having said that, you are trying to use the query string s as the parameter value for #iv. Instead you should ExecuteScalar in first and use the result of it in second.
However, you can both get the idviagem value and do the insert in one single statement like this:
string q = #"insert into tbpassageiro
(nome,cc,fotocc,idviagem)
select #n,#cc,#p,idViagem from tbviagem where dia like #dia";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.Add("#dia", SqlDbType.VarChar).Value = idatxt.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Note: I don't suggest using AddWithValue, prefer Add instead.
EDIT: For sampling with a Datetime dia field:
DateTime dt;
cmd.Parameters.Add("#dia", SqlDbType.DateTime);
if (DateTime.TryParse(idatxt.Text, out dt))
{
cmd.Parameters["#dia"].Value = dt;
}
else
{
cmd.Parameters["#dia"].Value = DBNull.Value;
}
If idatxt is for getting a date\datetime value it would be much easier to use DateTimePicker to get a valid DateTime value.
It looks like you are passing the query string s as the parameter value for #iv instead of the result of that query.
I suggest executing your command cmd and passing the result value to #iv:
string s = "select idviagem from tbviagem where dia like '" + idatxt.Text + "'";
cmd = new SqlCommand(s, con);
con.Open();
Int32 resultValue = (Int32) cmd.ExecuteScalar();
string q = "insert into tbpassageiro (nome,cc,fotocc,idviagem) values(#n,#cc,#p,#iv)";
cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.AddWithValue("#iv", resultValue);
cmd.ExecuteNonQuery();

Send Unicode string from MS Access to SQL Server using a DataSet

I am trying to get a string from a MS Access database and insert into a SQL Server database by using a dataset. But the utf8 string in my SQL statement inserted like ????????? - what can I about this?
This is my code:
OleDbCommand cmd2 = new OleDbCommand("select * from t_about_us", con_access);
OleDbDataAdapter da2 = new OleDbDataAdapter(cmd2);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "t_about_us");
con.Open();
string command2 = "insert into t_about_us(matn,see,metatag_description,metatag_keywords,metatag_author) values('" +
Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(ds2.Tables[0].Rows[0]["matn"].ToString())) + "','" +
Convert.ToInt32(ds2.Tables[0].Rows[0]["see"].ToString()) + "','" +
ds2.Tables[0].Rows[0]["metatag_description"].ToString() + "','" +
ds2.Tables[0].Rows[0]["metatag_keywords"].ToString() + "','" +
ds2.Tables[0].Rows[0]["metatag_author"].ToString() + "')";
SqlCommand cmdd2 = new SqlCommand(command2, con);
cmdd2.ExecuteNonQuery();
con.Close();
By using dynamic SQL to construct an SQL statement with sting literals like 'this' you are implicitly converting the string from Unicode into the single-byte character set used by the SQL Server, and any Unicode characters that do not map to that target character set will be replaced by question marks.
So, for example, with my SQL Server ...
cmd.CommandText = "INSERT INTO myTable (textCol) VALUES ('γιορτή')";
cmd.ExecuteNonQuery();
... will be inserted as ...
????t?
... even though [textCol] is defined as an NVARCHAR column.
The correct approach is to use a parameterized query, like so
cmd.CommandText = "INSERT INTO myTable (textCol) VALUES (#word)";
cmd.Parameters.Add("#word", System.Data.SqlDbType.NVarChar).Value = "γιορτή";
cmd.ExecuteNonQuery();
thank you my friends Finally my code work, this is answer:
OleDbCommand cmd2 = new OleDbCommand("select * from t_about_us", con_access);
OleDbDataAdapter da2 = new OleDbDataAdapter(cmd2);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "t_about_us");
con.Open();
SqlCommand cmd1 = new SqlCommand("INSERT INTO t_about_us(matn,see,metatag_description,metatag_keywords,metatag_author) VALUES (#matn,#see,#metatag_description,#metatag_keywords,#metatag_author)",con);
cmd1.Parameters.Add("#see", System.Data.SqlDbType.BigInt).Value = Convert.ToInt32(ds2.Tables[0].Rows[0]["see"].ToString());
cmd1.Parameters.Add("#matn", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["matn"].ToString();
cmd1.Parameters.Add("#metatag_description", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_description"].ToString();
cmd1.Parameters.Add("#metatag_keywords", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_keywords"].ToString();
cmd1.Parameters.Add("#metatag_author", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_author"].ToString();
cmd1.ExecuteNonQuery();
con.Close();

Dropdownbox.selectedvalue passing to sql comment

string ddorder = DropDownList2.SelectedValue; // column
string ddtype = DropDownList3.SelectedValue; //asc or desc
String str1 = "Select * from table1 order by("+ddorder+" "+ddtype+")";
//there is an error beacuse of ddtype, what am I doing wrong?
SqlCommand cmd = new SqlCommand(str1, con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = cmd;
DataSet ds1 = new DataSet();
da1.Fill(ds1, DropDownList2.SelectedValue);
GridView2.DataSource = ds1;
GridView2.DataBind();
con.Close();
As far as I can see, you don't need to use ( and ) in order by clause. It's syntax doesn't have any usage for ( or ).
For example;
order by id desc
will work but
order by (id desc)
won't work.
By the way, use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter automatically instead of calling Close method manually.
Also you don't need cmd.ExecuteNonQuery(); part for a SELECT statement. It is unnecessary since it's just execute your select query. It doesn't do or return something.
A few things more;
Change your table1 to something meaningful.
Don't use SELECT *. It's quite bad.
Use Dynamic Query:
Change Here:
string ddorder = DropDownList2.SelectedValue; // column
string ddtype = DropDownList3.SelectedValue; //asc or desc
String str1 = "exec(Select * from table1 order by "+ddorder+" "+ddtype+")";
and
SqlCommand cmd = new SqlCommand(str1, con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = cmd;
DataSet ds1 = new DataSet();
da1.Fill(ds1);
GridView2.DataSource = ds1;
GridView2.DataBind();
con.Close();
Remove the parenthesis in the "order by" clause:
String str1 = "Select * from table1 order by "+ddorder+" "+ddtype;

C# mysql parameterized query

I have this peace of code where I need to retrieve data from Mysql. If I use parameterized query it does not take actual parameter value instead it takes parameter name as value.
Error: #choise must be defined
MySqlConnection connection = new MySqlConnection("");
MySqlDataAdapter mySqlDataAdapter;
DataSet DS;
private string columnValue = xxx;
private string Choise = yyy;
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM table2 WHERE " + columnValue + " = #choise";
command.Parameters.Add(new MySqlParameter("#choise", Choise));
DS = new DataSet();
connection.Open();
mySqlDataAdapter = new MySqlDataAdapter(command.CommandText, connection);
mySqlDataAdapter.Fill(DS);
connection.Close();
when I run this i get query like:
SELECT * FROM table2 WHERE xxx = #choise
instead of
SELECT * FROM table2 WHERE xxx = yyy.
Where is the problem?
I have tried:
command.Parameters.Add(new MySqlParameter("#choise", Choise));
command.Parameters.AddWithValue("#choise", Choise);
It works fine when I'm using actual variables instead of parameters.
I think you need to run Prepare() on the command before adding parameters:
command.CommandText = "select * from table2 where " + columnValue + " = #choise";
command.Prepare();
command.Parameters.AddWithValue("#choise", Choise);
Try this instead:
command.CommandText = "SELECT * FROM `table2` WHERE `" + columnValue + "` = #choise";
command.Parameters.AddWithValue("#choise", Choise);

C# SQL Server query

This is code segment that I have written in C#. Mobile and Name are columns in my table.
The problem is that there is something wrong with format of my query. Is the syntax correct if we want to connect two queries in C # using OR?
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM [Contact Management] WHERE
Mobile='"+Convert.ToInt32(txtSearch.Text)+"' OR Name='"+txtSearch.Text+"'",con);
No, that syntax is not correct. It's vulnerable to sql injection attacks. You need to build it like this:
SqlCommand cmd = new SqlCommand("SELECT * FROM [Contact Management] WHERE
Mobile= #Search OR Name= #Search")
SqlDataAdapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add("#Search", SqlDbType.NVarChar, 50).Value = txtSearch.Text;
You could also write the query this way:
SELECT * FROM [Contact Management] WHERE #Search IN (Mobile, Name)
As usual, never use string concatenation to build sql command. Use parametrized queries
string query = "SELECT * FROM [Contact Management] WHERE Mobile=#mobile OR Name=#name";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#mobile", Convert.ToInt32(txtSearch.Text));
cmd.Parameters.AddWithValue("#name", txtSearch.Text);
SqlDataAdapter da= new SqlDataAdapter (cmd);
The parametrized query will save your database from Sql Injection Attacks, but also from problems in parsing your input text. What if in the search text you have a single quote? You will get a syntax error with concatenation.
However, let me say that your code will fail before this. If you have a number in your txtSearch, then everything will work, but if you have a string. converting to a number with Convert.ToInt32 will fail. Better to use
SqlCommand cmd = new SqlCommand();
string query;
int numSearch;
if(Int32.TryParse(txtSearch.Text, out numSearch))
{
query = "SELECT * FROM [Contact Management] WHERE Mobile=#p1";
cmd.Parameters.AddWithValue("#p1", numSearch);
}
else
{
query = "SELECT * FROM [Contact Management] WHERE Name=#p1";
cmd.Parameters.AddWithValue("#p1", txtSearch.Text);
}
cmd.CommandText = query;
....

Categories