Query with parameters works perfectly in ms access database. But when I supply the same parameters from C# winforms application it returns no records.
If the parameter is passed to the query then it will use that parameter in where clause, otherwise it will retrieve all records.
bus table sample data:
Ms-Access Query:
PARAMETERS parPlateNo Text ( 255 );
SELECT bus.*
FROM bus
WHERE (((bus.plateNo) Like IIf(IsNull([parPlateNo]), True ,"%" & [parPlateNo] & "%")));
C# Code:
using (OleDbConnection conn = new OleDbConnection(myGlobals.connString))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter())
{
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "qryBus";
if(plateNo == "")
cmd.Parameters.AddWithValue("?", DBNull.Value);
else
cmd.Parameters.AddWithValue("?", plateNo);
adapter.SelectCommand = cmd;
dsDetails = new DataSet();
adapter.Fill(dsDetails, "details");
}
}
}
PlateNo is a text column.
Remarks: If I remove the like statement in ms access query and run the same code in C#, it will run perfectly and retrieve all the records in table.
After that, I display the data in datagridview using bindingsource.
Why this is happening?
You using oleDB. You have to change that query and use % as wild cards. DAO, and native Access you use *, but for ADO, or oleDB, you have to use % as the wild cards.
Here are a couple of examples that should help you get this up and running.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("insert into [dbo].[Student] values(#a,#b,#c)", con);
cmd.Parameters.AddWithValue("#a", int.Parse(textBox1.Text));
cmd.Parameters.AddWithValue("#b", textBox2.Text);
cmd.Parameters.AddWithValue("#c", textBox3.Text);
con.Open();
a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Data Submited");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
AND
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("select * from student where sid=#a", con);
cmd.Parameters.AddWithValue("#a",int.Parse(comboBox1.SelectedItem.ToString()));
con.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
textBox1.Text = dr["sid"].ToString();
textBox2.Text = dr["fname"].ToString();
textBox3.Text = dr["lname"].ToString();
//label1.Text = dr["cdate"].ToString();
}
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
Related
I have a Datagridview that updates using a Datasource. I'm trying to refresh the Datagridview after the CellEndEdit event. Everything works perfectly, but Datagridview is not refreshing. Below is my c# code.
private void GridDetails_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == GridDetails.Columns["Name"].Index)
{
string ID = GridDetails.Rows[e.RowIndex].Cells["ID"].Value.ToString();
string Name = GridDetails.Rows[e.RowIndex].Cells["Name"].Value.ToString();
using (SqlConnection connection = new SqlConnection(.........)) // SqlConnection
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
connection.Open();
cmd.Parameters.Clear();
cmd.CommandText = "Update MyTable SET Name=#Name,LastModifiedDate=GETDATE() WHERE RecID=#ID";//Update Query
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
connection.Close();
GridDetails.Refresh(); // this is not working
}
}
}
}
i have the following code below and what im trying to do is on the comboBox there is "ID" from my database and this ID represents every survey detail that Admin used to create so when the user goes to view the survey they click on the survey number in comboBox and the labels will change according to the database. I tried it with the below code but unfortunatley all it seems to do is grab a random one, if someone could help that would be amazing. It doesnt have to be like below, just as long as it works,
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey ";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
You can try this to search data from database using Combobox
I use parameterized query to avoid SQL Injection
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey WHERE [ColumnName] = #ComboBoxValue";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#ComboBoxValue", comboBox1.SelectedIndex.ToString())
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
I am working on a news based site. And the site has a search bar for the Newstitle and I don't want to let SQL injections happen on it.
What I am doing is to get the text from the textbox and then use a query to fetch the matching results. This is what happens when a user clicks the search button:
protected void button_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
try
{
SqlCommand comm = new SqlCommand("SELECT * FROM news
Where newstilte LIKE '%" + searchbox.text + "%'", conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
myRepeater.DataSource = reader;
myRepeater.DataBind();
reader.Close();
}
catch (Exception exception)
{
Response.Write(exception.ToString());
}
finally
{
conn.Close();
}
}
As you can see I then use a repeater to show the results. I am wondering how can I prevent SQL injection in the part where people write in the textbox.
USE PARAMETRIZED QUERIES AS BELOW:
protected void button_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
try
{
SqlCommand comm = new SqlCommand("SELECT * FROM news
Where newstilte LIKE '%' + #newstilte + '%'", conn);
cmm.Parameters.AddWithValue("#search",searchbox.text) ;
conn.Open();
SqlDataAdapter reader = comm.ExecuteReader();
myRepeater.DataSource = reader;
myRepeater.DataBind();
reader.Close();
}
catch (Exception exception)
{
Response.Write(exception.ToString());
}
finally
{
conn.Close();
}
}
EDIT:
You can also use following if you have datatype kind of restriction for search.
cmm.Parameters.Add(new SqlParameter("#search", SqlDbType.VarChar));
cmm.Parameters["#search"].Value = searchbox.text;
Have a look at THIS doccument.
Try
SqlCommand comm = new SqlCommand("SELECT * FROM news
Where newstilte LIKE '%' + #newstilte + '%'", conn);
comm.Parameters.AddWithValue("#newstilte",searchbox.text)
Use stored procedures with parameters.
.net SQL library properly
SqlCommand comm = new SqlCommand("StoredProcedureName")
comm.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Parameter", Value)
The .net library should handle most injections.
Hi i want to basically insert the values in the labels to a table in ms access.
I have done it for textbox and it stores but for Label When i try to store it no error shows up but it does not store in the database what should i do? I am using the following code
static OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
OleDbDataAdapter ada = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader dr;
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string str = "insert into Orders (Products, Amount)" + " values (#p1, #p2)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", Label18.Text);
cmd.Parameters.AddWithValue("#p2", Label16.Text);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
Console.WriteLine("Exception Occured");
}
finally
{
if (con != null && con.State != ConnectionState.Closed)
{ con.Close(); }
}
}
Also i tried storing textbox value into the same Table "Orders" under the column "Address" but facing the same above issue...The table does not update. I have used this code before for other textboxes etc for different tables and it has worked fine..
static OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
OleDbDataAdapter ada = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader dr;
protected void Button1_Click(object sender, EventArgs e)
{
{
string str = "insert into Orders (Address)" + " values (#p1)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement
try with
string str = "insert into Orders (Products, Amount) values (?,?)";
You can change the code as below
protected void Button1_Click(object sender, EventArgs e)
{
try
{
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb"))
using (OleDbCommand cmd = new OleDbCommand("insert into Orders (Products, Amount) values (?,?)", con))
{
cmd.Parameters.AddWithValue("#p1", Label18.Text);
cmd.Parameters.AddWithValue("#p2", int.Parse(Label16.Text));
con.Open();
int no = cmd.ExecuteNonQuery();
Console.WriteLine("number of rows affected = " + no);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception Occured :" ex.ToString());
}
}
Im trying to update my database by using datagridview there is no error but there are no changes made when i Click on Save button.Can you help me here.. Here is my code
Thanks in advance. .
private void EditRecord_Load(object sender, EventArgs e) {
LoadData();
}
void LoadData() {
string query = "SELECT *FROM Record";
SqlDataAdapter da = new SqlDataAdapter(query, con);
SqlCommandBuilder sbuilder = new SqlCommandBuilder(da);
DataTable dtable = new DataTable();
da.Fill(dtable);
BindingSource bsource = new BindingSource();
bsource.DataSource = dtable;
dgv.DataSource = bsource;
}
private void btnSave_Click(object sender, EventArgs e) {
if (dgv.RowCount > 1) {
for (int x = 0; x < dgv.RowCount - 1; x++) {
if (dgv.Rows[x].Cells[0].Value.ToString() == "") {
SqlCommand cmdSave = new SqlCommand("UPDATE tblRecord SET FName=#FName, Address=#Address, ContactNo=#ContactNo WHERE IdNo=#IdNo", con);
{
cmdSave.Parameters.Add("#IdNo", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[0].Value;
cmdSave.Parameters.Add("#FName", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[1].Value;
cmdSave.Parameters.Add("#Address", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[2].Value;
cmdSave.Parameters.Add("#ContactNo", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[3].Value;
}
con.Open();
cmdSave.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Updated!");
}
}
}
LoadData();
}
The query in LoadData() function must have a space ' ' after the '*'. It is also advised to use a try catch block on your update operation. Also instead of running select *, it is always preferred to select the needed columns like
select column1,column2 from myTable;
string query = "SELECT * FROM Record";
try{
//open connection
//Excecute your command
}
catch (SqlException ex)
{
//Log exception(ex)
// throw ex
}
finally
{
// Check if connection not null then close connection
}
It should be
private void btnSave_Click(object sender, EventArgs e) {
if (dgv.RowCount >= 1) {
for (int x = 0; x < dgv.RowCount - 1; x++) {
if (dgv.Rows[x].Cells[0].Value.ToString()!="" && dgv.Rows[x].Cells[0].Value!=null) {
SqlCommand cmdSave = new SqlCommand("UPDATE tblRecord SET FName=#FName, Address=#Address, ContactNo=#ContactNo WHERE IdNo=#IdNo", con);
{
cmdSave.Parameters.Add("#IdNo", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[0].Value.ToString();
cmdSave.Parameters.Add("#FName", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[1].Value.ToString();
cmdSave.Parameters.Add("#Address", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[2].Value.ToString();
cmdSave.Parameters.Add("#ContactNo", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[3].Value.ToString();
}
con.Open();
cmdSave.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Updated!");
}
}
}
There is a much easier way to do this by using a command builder.
As your binding the DataGridView to your DataTable, any changes in the DGV are reflected into the DataTable. Therefore, you can use a command builder to save changes back.
If you look at my example below, from giving the command builder the SELECT command, it can generate the other relevant commands it needs to perform, INSERT, UPDATE & DELETE.
You just need to make sure that the DataTable is Public or accessible.
Use something like this on your btnSave_Click :-
using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["con"]))
{
var adaptor = new SqlDataAdapter();
adaptor.SelectCommand = new SqlCommand("SELECT * FROM [Record]", con);
var cbr = new SqlCommandBuilder(adaptor);
cbr.GetDeleteCommand();
cbr.GetInsertCommand();
cbr.GetUpdateCommand();
try
{
con.Open();
adaptor.Update(dtable);
MessageBox.Show("Changes Saved","Information");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "SqlException Error");
}
catch (Exception x)
{
essageBox.Show(x.Message, "Exception Error");
}
}
}