Adding a Where Clause to a OleDbCommand - c#

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);

Related

Sql Exception related to DataSet in asp.net

I want to get values of a id specified row in my "Service Fees" table. When I try to execute following code an exception, which says "An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code.Additional information: Incorrect syntax near 'a34'."
Is it about Dataset object?
PS: The id is; ee83089d-4a34-46e0-be6c-b8b506f31a8e
if (Request.QueryString["MyId"] != null)
{
isUpdate = true;
var id = Request.QueryString["MyId"].ToString();
SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id=" + id, connection);
SqlDataAdapter adapter2 = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
adapter2.Fill(ds);
sf1.name = ds.Tables[0].Rows[0][1].ToString();
}
Enclose your id in single quote, it should look like :
SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id='" + id +"'", connection);
Id is GUID and it should be enclosed within single quotes.
SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id= #id", connection);
cmd2.Parameters.Add(new SqlParameter("id",id));
to avoid sql injection.
Beware of SQL Injection
Dont pass parameters in single quotes,Double quotes
Always use SqlParameter Class
As your Parameter is String You need to Pass it As string DataType
string Id="ee83089d-4a34-46e0-be6c-b8b506f31a8e";
SqlParameter para1=new SqlParameter("#Id",SqlDbType.Varchar,500);
para1.Value=Id;
SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id=#Id" , connection);
cmd2.Parameters.Add(para1);
SqlDataAdapter adapter2 = new SqlDataAdapter(cmd2);
You're passing the id unquoted to SQL.
As a result it's probably trying to calculate the result of ee83089d-4a34-46e0-be6c-b8b506f31a8e.
You probably want:
SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id='" +
id + "'", connection);
Or some other SQL call which isn't vulnerable to injection attacks.

Incrementing an int during insert

I'm trying to increment an integer in an MS Access table from a c# .net page during insert.
I'm getting a syntax error when attempting the following. Also unsure if I should be using an ExecuteNonQuery() or not?
OleDbCommand cmd = new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget)", conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
You miss a bracket after tblTarget:
OleDbCommand cmd =
new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))", conn);
Here is a little review of your code, try using the using pattern:
using(var conn = new Connection())
{
conn.Open();
string sql = "INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}
You're missing a bracket, try:
INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))
But I think you are going to have other issues, you need something closer to this:
INSERT INTO tblTarget ( target, ref )
SELECT #target AS Targ, First((SELECT MAX(ref)+1 FROM tblTarget)) AS MaxRef
FROM tblTarget
GROUP BY #target;
The correct way to achieve your goal is
string sql = "INSERT INTO tblTarget (target,ref) " +
"SELECT ?, MAX(ref)+1 FROM tblTarget";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
I would not do the increment by the sql or code, we can use AutoNumber data type for auto increase the value in access.
string sql = "INSERT INTO tblTarget(target) VALUES(#target)";
using(var conn = new Connection())
using(OleDbCommand cmd = new OleDbCommand(sql, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}

SqlDataAdapter, SqlCommand dropping the leading numbers from string

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.

"Data type mismatch in criteria expression" when trying to delete row from database

OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE(ID= '" +
txtStudentIDnumber.Text + "')";
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
In your command text you need to remove single quotes (') around the txtStudentIDnumber.Text as it appears ID is of type integer and you are passing it as string. Following should fix the error.
system.CommandText = "DELETE FROM Student WHERE(ID= " + txtStudentIDnumber.Text + ")";
EDIT: With respect to #mdb comments, you should always use Parameters in your query so that you can avoid SQL Injection. Consider the following:
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID = ?";
OleDbParameter parameter = new OleDbParameter("ID", txtStudentIDnumber.Text);
system.Parameters.Add(parameter);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID=#ID";
system.Parameters.AddWithValue("#ID", txtStudentIDnumber.Text);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
What will happen when user input for txtStudentIDNumber is,
1 or 1=1
In that case hardcoded SQL string will be,
DELETE FROM Student WHERE(ID=1 or 1=1)
So prefer parameterized sql statement instead of hard-coded string.
using(OleDbConnection cn=new OleDbConnection(cnStr))
{
using(OleDbCommand cmd=new OleDbCommand())
{
cmd.CommandText="DELETE FROM Student WHERE ID=#ID";
cmd.Connection=cn;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value=txtStudentIDnumber.Text;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}

Enter data to particular column in sql

I have a text box that retrieve email from membership table in database. User may edit their email and update the new email. My question is, how to replace the old email with the new one? What is the query for sql?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into aspnet_membership("i dont know how whether to write all columns or only email);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", Textbox2.Text);
My question is, how to replace the old email with the new one?
You need an UPDATE in this case, instead of an INSERT:
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET
email = #email WHERE userID = #userID", conn);
It will work like any other simple update SQL Query:
update TableName set Columname = #Value where Username = #Value
Try this:
You may need UserId, and new Email to replace existing email address for the given existing user.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET email = #newEmail WHERE UserID = #userID");
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", Textbox2.Text);
cmd.Parameters.AddWithValues("#UserId", YourUserId);
conn.open();
cmd.ExecuteNonQuery();
conn.close();
you need to use update query and not insert query.
see syntax here:
http://www.w3schools.com/sql/sql_update.asp
check this link from MSDN http://msdn.microsoft.com/en-us/library/ms186862.aspx
SELECT REPLACE('abcdefghicde','cde','xxx');
GO
As you want to Update EmailID so your query should be
SqlCommand cmd = new SqlCommand("Update aspnet_membership set email=#email where UserID=#UserID");
This should work for you, because your Insertquery which you are trying, this will always insert a new record instead of updating older records..

Categories