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;
....
Related
I am trying to add a where clause to the following line of code.
the reason for this is because i get the datatable from a dropdown combobox. now i want to filter that table on user name, so that only the user can see their records.
i need help on how to write the where clause into this code.
if you need any more information i will gladding add it.
thank you for any help.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ", comboBox1.Text), con);
After Comments
i added the sql injection protection.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From
#Companydetails where Research_ID = #Researcher_ID"), con);
cmd.Parameters.AddWithValue("#Companydetails", comboBox1.Text);
cmd.Parameters.AddWithValue("#Researcher_ID", usernumber_lab.Text);
but now it is giving me a error saying:
Additional information: Syntax error in query. Incomplete query clause.
is there something else i need to add to finnish this query off?
I would do it as follows;
string query = "Select * from MyTable Where username = #username";
using (OleDbCommand cmd = new OleDbCommand(query, con))
{
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = comboBox1.Text;
}
This way the object will dispose automatically and also you'll be safe from Sql Injection
Please try this
string sql = String.format("Select * From {0} where id = {1}", comboBox1.Text, id);
OleDbCommand cmd = new OleDbCommand(sql,con);
You can just make your sql statement longer:
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From table Where something = something", comboBox1.Text), con);
You don't have to work with multiline or anything. This is only needed in some database managers, but not in a c# sql statement.
If you would like
OleDbCommand cmd = new OleDbCommand(String.Format("Select * From {0} WHERE username='{1}'", comboBox1.Text,username.Text), con);
You can try the below code
OleDbCommand cmd = new OleDbCommand(string.Format(
"SELECT * FROM {0} WHERE Username = '{1}'",
comboBox1.Text, userName), con);
I have a example: I am using C# to solve Oracle database problem
cmd = new OracleCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select DATE_START from EMPLOYEE;";
It works successfull.
BUt when I use GROUP BY, it doesm't work.
cmd = new OracleCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select DATE_START from EMPLOYEE GROUP BY DATE_START;";
It doesn't work
ORA-00911: invalid character.
Thanks so much
Try removing the semicolon(;) from CommandText like
cmd.CommandText = "select DATE_START from EMPLOYEE GROUP BY DATE_START";
//^^ From Here
I am not sure why it should be a problem, but I have seen similar issue before with Oracle + ADO.Net.
Also, if you are not using any aggregate methods then you can use DISTINCT keyword instead of GROUP BY like:
cmd.CommandText = "SELECT DISTINCT DATE_START from EMPLOYEE";
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 + "%");
I am trying to execute a SQL statement with a where clause which looks like
string s2 = "Select * from idtyfile where oysterid=" + id ;
SqlCommand da2 = new SqlCommand(s2, con); or
SqlAdapter da2 = new SqlAdapter(s2, con);
Both of these are failing when I am trying to execute them
da2.ExecuteReader();
the data in ID looks like
ID
43PCOU5T
ZP6RAEJ0
For some reason both of these queries are failing on these kind of data.
You are missing the single quotes in your select command which is what is making your original SELECT fail. However I would like to note that you should always parameterize and encapsulate your SqlCommand / SqlConnection in a using statement. The following would be a cleaner more secure way to solve your problem.
string s2 = "Select * from idtyfile where oysterid=#id";
DataTable myDataTable = new DataTable();
using (SqlConnection conn = new SqlConnection(myConnectionString))
using (SqlCommand cmd = new SqlCommand(s2, conn))
{
cmd.Parameters.AddWithValue("#id", id);
conn.Open();
myDataTable.Load(cmd.ExecuteReader());
}
For some educational resources, you should look at the following links.
MSDN Reference for the using keyword
MSDN Reference for SqlCommand -- Look at the Parameters property.
I have two columns syntax and query in my table Table1. Syntax contains data called po and a query called select * from po_pomas_pur_order_hdr where pomas_pono =. I got this query value by using
SqlDataAdapter da = new SqlDataAdapter("select query from Table1 where syntax = '" + textBox1.Text + "'", conn);
And my problem is that I need to dynamically pass another value inside the query which I retrived using dataadapter like this:
SqlDataAdapter da1 = new SqlDataAdapter(da.tostring() +"'"+ textBox1.Text +"'", conn)
The resulting query should be like this:
select * from po_pomas_pur_order_hdr where pomas_pono = '2PO/000002/09-10'
But it is not possible. How to get a query like this? Any suggestion?
SqlDataAdapter is used to fill datasets and datatables. You cannot obtain the result of a query with ToString(). I think you want to use SqlCommand to execute your first query to retrieve the actual query to run from the database like this:
string query = null;
using (var command = new SqlCommand("select query from Table1 where syntax = #Syntax", conn))
{
command.Parameters.AddWithValue("#Syntax", textBox1.Text);
query = command.ExecuteScalar(); // this assumes only one query result is returned
}
Then you can use the data adapter to fill it:
SqlDataAdapter da1 = new SqlDataAdapter(query +"'"+ textBox1.Text +"'", conn);
Although I would suggest to use parameters for that as well.
in this way is more safe: dotnetperls
He check the "'" and the "\", check the type of the fields etc...
Code from the example above (is the same for insert delete and update):
using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Name", dogName));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int weight = reader.GetInt32(0);
string name = reader.GetString(1);
string breed = reader.GetString(2);
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}", weight, name, breed);
}
}
I suggest you to use SqlParameters. Here is example how to use DataAdapter and parameters.
Provided that you have a DataSet you intend to fill using the adapter and that you adjust the queries to use parameters in order to avoid sql injection you should be able to use something like this:
string query;
using(var sqlCommand = new SqlCommand(
"select query from Table1 where syntax=#syntax", conn))
{
sqlCommand.Parameters.AddWithValue("syntax", textBox1.Text);
query = (string)sqlCommand.ExecuteScalar();
}
using(var dataAdapter = new SqlDataAdapter())
using(var dataCommand = new SqlCommand(query, conn))
{
dataCommand.Parameters.AddWithValue("parameter", poNumber);
dataAdapter.SelectCommand = dataCommand;
dataAdapter.Fill(myDataSet);
}