I have an access database connected to my project and want to save back edits. The edits only seem to save when existing values are being modified. When I insert a row or delete a row using my binding navigator, It does not update my database. I have tried many queries:
try
{
query = string.Format("SELECT * FROM {0}", Text);
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.InsertCommand = new OleDbCommand(query, conn);
adapter.DeleteCommand = new OleDbCommand(query, conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(Account);
Console.WriteLine("Saved");
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException + ":" + ex.Message);
}
In a DataGridView.RowAdded event I added the following code:
try
{
string AccNum = accountGridView.Rows[e.RowIndex].Cells[0].Value.ToString();
string lName = accountGridView.Rows[e.RowIndex].Cells[1].Value.ToString();
string fName = accountGridView.Rows[e.RowIndex].Cells[2].Value.ToString();
string balance = accountGridView.Rows[e.RowIndex].Cells[3].Value.ToString();
adapter.InsertCommand = new OleDbCommand("INSERT INTO " + Text + " VALUES ("
+ AccNum + ", " + lName + ", " + fName + ", " + balance + ")", conn);
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.DeleteCommand = new OleDbCommand(query, conn);
adapter.Update(Account);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ":" + ex.InnerException);
}
In my RowAdded Event, it gives me an error and in my regular save event, everything works just fine besides the Insert and Delete Commands. Does anyone know the queries I can use to make this work?
I solved my problem by removing my RowsAdded event and all the InsertCommands and DeleteCommands. I think the problem was I was overriding the default InsertCommands and DeleteCommands with bad SqlCode.
I've created some sort of application that keeps a database of employees and their payments. It works well so far. But now I'm trying to implement an "update" feature, if there is some data that changes for specific user.
So I wrote the following code for the update, but I get this error:
CommandText property has not been initialized at line 105: "cmd.ExecuteNonQuery();"
Thanks !
var connString = #"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
var query = "UPDATE info SET Nume='" + textBox5.Text + "' AND Prenume='" + textBox4.Text + "' AND Data='" + dateTimePicker1.Value.ToShortDateString() + "' AND Proiect='" + textBox1.Text + "' AND Schimburi='" + label10.Text + "' AND Poza=#Poza AND Acord='" + textBox2.Text + "' AND Baza='" + textBox3.Text + "' WHERE Nume='" + label8.Text + "' AND Prenume='" + label5.Text + "'";
cmd.ExecuteNonQuery();
MessageBox.Show("Salvat cu succes!");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You must set cmd.CommandText
//Codes
cmd.CommandText = query;
cmd.ExecuteNonQuery();
MessageBox.Show("Salvat cu succes!");
this.Close();
Add cmd.CommandText = query; above your Execution.
I have declared the scalar already but I am still getting the error. My code checks to see if an entry exists, if it does it updates the entry or if it does not exist it creates a new entry:
try
{
string server = Properties.Settings.Default.SQLServer;
string connection = "Data Source=" + server + ";Initial Catalog=Propsys;Persist Security Info=True;User ID=sa;Password=0925greg";
using (SqlConnection cn = new SqlConnection(connection))
{
cn.Open();
SqlCommand cmdCount = new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #" + this.contactPersonTextBox.Text, cn);
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
SqlDataReader myReader;
myReader = cmdCount.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count > 0)
{
string query = "UPDATE _1Agent SET DealID = #DealID, \n" +
"ContactPerson = #ContactPerson, \n" +
"Address = #Address, \n" +
"TaxVatNo = #TaxVatNo, \n" +
"Comm = #Comm, \n" +
"WorkTel = #WorkTel, \n" +
"Cell = #Cell, \n" +
"Fax = #Fax, \n" +
"Email = #Email, \n" +
"Web = #Web, \n" +
"CreateDate = #CreateDate, \n" +
"Notes = #Notes WHERE id = #id";
SqlCommand cm = new SqlCommand(query);
string Contact = contactPersonTextBox.Text;
cm.Parameters.AddWithValue("#DealID", txtDealNo.Text);
cm.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
cm.Parameters.AddWithValue("#Address", addressTextBox.Text);
cm.Parameters.AddWithValue("#TaxVatNo", taxVatNoTextBox.Text);
cm.Parameters.AddWithValue("#Comm", commTextBox.Text);
cm.Parameters.AddWithValue("#WorkTel", workTelTextBox.Text);
cm.Parameters.AddWithValue("#Cell", cellTextBox.Text);
cm.Parameters.AddWithValue("#Fax", faxTextBox.Text);
cm.Parameters.AddWithValue("#Email", emailTextBox.Text);
cm.Parameters.AddWithValue("#CreateDate", DateTime.Now);
cm.Parameters.AddWithValue("#Notes", notesTextBox.Text);
cm.CommandText = query;
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Saved...", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
else
{
string query1 = "INSERT INTO _1Agent (DealID, \n" +
"ContactPerson, \n" +
"Address, \n" +
"TaxVatNo, \n" +
"Comm, \n" +
"WorkTel, \n" +
"Cell, \n" +
"Fax, \n" +
"Email, \n" +
"CreateDate, \n" +
"Notes) VALUES ('" + txtDealNo.Text + "',\n" +
"'" + contactPersonTextBox.Text + "',\n" +
"'" + addressTextBox.Text + "',\n" +
"'" + taxVatNoTextBox.Text + "',\n" +
"'" + commTextBox.Text + "',\n" +
"'" + workTelTextBox.Text + "',\n" +
"'" + cellTextBox.Text + "',\n" +
"'" + faxTextBox.Text + "',\n" +
"'" + emailTextBox.Text + "',\n" +
"'" + notesTextBox.Text + "',\n" +
"'" + DateTime.Now + "')";
SqlCommand cm = new SqlCommand(query1);
string Contact = contactPersonTextBox.Text;
cm.Parameters.AddWithValue("#DealID", txtDealNo.Text);
cm.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
cm.Parameters.AddWithValue("#Address", addressTextBox.Text);
cm.Parameters.AddWithValue("#TaxVatNo", taxVatNoTextBox.Text);
cm.Parameters.AddWithValue("#Comm", commTextBox.Text);
cm.Parameters.AddWithValue("#WorkTel", workTelTextBox.Text);
cm.Parameters.AddWithValue("#Cell", cellTextBox.Text);
cm.Parameters.AddWithValue("#Fax", faxTextBox.Text);
cm.Parameters.AddWithValue("#Email", emailTextBox.Text);
cm.Parameters.AddWithValue("#CreateDate", DateTime.Now);
cm.Parameters.AddWithValue("#Notes", notesTextBox.Text);
cm.CommandText = query1;
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Saved...", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Your usage of parameter is wrong, it should be:
SqlCommand cmdCount =
new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson", cn);
Later you are adding the parameter correctly.
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
To get the count use SqlCommand.ExecuteScalar, instead of using DataReader:
int count = (int) cmdCount.ExecuteScalar();
For the other queries, UPDATE and INSERT, you can use a verbatim string, instead of concatenating strings over multiple lines.
string query = #"UPDATE _1Agent SET DealID = #DealID,
ContactPerson = #ContactPerson,
Address = #Address,
TaxVatNo = #TaxVatNo,
Comm = #Comm,
WorkTel = #WorkTel,
Cell = #Cell,
Fax = #Fax,
Email = #Email,
Web = #Web,
CreateDate = #CreateDate,
Notes = #Notes WHERE id = #id";
Other issues with the code:
You are concatenating strings to form INSERT query, later you are adding parameters, follow the same convention as UPDATE query and then use the parameters.
As pointed out in the other answer, you are not adding parameter#id value for UPDATE command
You are not specifying connection property with your UPDATE and INSERT command:
Specify it like
SqlCommand cm = new SqlCommand(query, cn);
Consider enclosing Connection and Command object in using
statement as it will ensure the proper disposal of unmanaged resources.
I see a few things;
Don't use string concatenation with # sign for parameters. That's wrong usage. Use it like;
"SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson"
and
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
and use ExecuteScalar to get first column of the first row. Using a reader is unnecessary for this command.
Your UPDATE query requires #id value since you declare it in your command as;
cm.Parameters.AddWithValue("#id", yourIDvalue);
Your INSERT query, you never declare your parameters in your command. You just concatenate them with their values. And use verbatim string literal to generate multiline strings instead of using \n.
Please
Read more carefully about parameterized queries and how you can use them.
Give me parameterized SQL, or give me death
You forget to mention parameter name in your select query
SqlCommand cmdCount = new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson", cn);
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
There are some wrong things .So you can refer #Soner Gönül and #habib answers
And change your insert query.Since you have declared paramertes but you didn't define.So change as follows
string query1 = "INSERT INTO _1Agent (DealID,ContactPerson,Address,TaxVatNo,
Comm, WorkTel, Cell, Fax, Email,Notes,CreateDate)
VALUES ( #DealID , #ContactPerson,#Address ,#TaxVatNo ,
#Comm,#WorkTel , #Cell,#Fax,#Email,#Notes,#CreateDate)";
The current program I am building is used to save invoices and I want to save data into a database. However instead of repeating this code shown below 20 times for each possible entry i would like to create a function with the text box name changing in the function.
All the text boxes are named with a number at the end from 1 to 20. I was wondering if there is a way to have a function that would change the number at the end and if its even worth doing compared to repeating this 20 times.
if (txtProductID1.Text.Length > 0)
{
OleDbConnection oledbconnection1 = new OleDbConnection();
oledbconnection1.ConnectionString = Con;
OleDbCommand cmd;
String strInsert = "";
//Generate SQL Statement
strInsert = "Insert into [InvoiceOrder] Values (";
strInsert += "'1', ";
strInsert += "'" + txtInvoiceNo.Text + "', ";
strInsert += "'" + txtProductDescription1.Text + "', ";
strInsert += "'" + txtOrderNo1.Text + "', ";
strInsert += "'" + cboUnit1.Text + "', ";
strInsert += "'" + txtAmount1.Text + "', ";
strInsert += "'" + txtPrice1.Text + "', ";
strInsert += "'" + txtSum1.Text + "', ";
strInsert += "'" + txtDiscount1.Text + "' ";
strInsert += ")";
try
{
oledbconnection1.Open();
cmd = new OleDbCommand();
cmd.CommandText = strInsert;
cmd.Connection = oledbconnection1;
cmd.ExecuteNonQuery();
//MessageBox.Show("Record saved");
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.ToString());
}
finally
{
oledbconnection1.Close();
}
}
First, parameterize your query. Aside from security, the query you're building up is going to trip you up when you forget a single apostrophe somewhere.
As for iterating through the controls, perhaps Controls.Find() will work for you. The following code assumes all controls have a number from 1 to 20, and each number occurs once and only once on the form. (In your example, txtInvoiceNo does not have a number - I assume that's a typo.)
I made a few other changes too, like replacing your finally block with a using block, which will close and dispose your connection for you.
for (var i = 1; i <= 20; i++)
{
if (!String.IsNullOrEmpty(Controls.Find("txtProductID" + i, true).Single().Text))
{
using (var oledbconnection1 = new OleDbConnection())
{
oledbconnection1.ConnectionString = Con;
oledbconnection1.Open();
var insertStatement =
"Insert into [InvoiceOrder] Values ('1', #InvoiceNo, #ProductDesc, #OrderNo, #Unit, #Amount, #Price, #Sum, #Discount)";
try
{
using (var cmd = new OleDbCommand(insertStatement, oledbconnection1))
{
cmd.Parameters.AddWithValue("#InvoiceNo", Controls.Find("txtInvoiceNo" + i, true).Single().Text);
...
...
cmd.Parameters.AddWithValue("#Discount", Controls.Find("txtDiscount" + i, true).Single().Text);
cmd.ExecuteNonQuery();
//MessageBox.Show("Record saved");
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.ToString());
}
}
}
}
protected void save_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
try
{
string connString = "Provider=OraOLEDB.Oracle;Data Source=127.0.0.1;User ID=SYSTEM;Password=SYSTEM;Unicode=True";
conn = new OleDbConnection(connString);
conn.Open();
string strQuery = "update login set fname ='" + TextBox4.Text + "' and lname='" + TextBox5.Text + "' and place='" + TextBox6.Text + "' and dob='" + TextBox7.Text + "' where uname='" + Label1.Text + "'";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
OleDbDataReader obReader = obCmd.ExecuteReader();
}
catch (OleDbException ex)
{
Response.Write("Send failure: " + ex.ToString());
}
catch (Exception exe)
{
Response.Write(exe.Message);
}
finally
{
if (null != conn)
{
conn.Close();
}
}
}
the update query syntax is wrong.
You cannot use AND while setting multiple columns. It should be seperated by comma.
string strQuery = "update login set fname ='" + TextBox4.Text + "',lname='" +
TextBox5.Text + "',place='" + TextBox6.Text + "',dob='" + TextBox7.Text +
"' where uname='" + Label1.Text + "'";
The values must be separated with a comma and there is one big problem in this code. Imagine what happens when someone puts the following into TextBox4:
' where 1 = 1 --
The result would be a table where all entries would be overwritten
update login set fname ='' where 1 = 1 --', lname='bla' ....
Use DbParameter instead:
string strQuery = #"
update LOGIN set
FNAME = :FNAME,
LNAME = :LNAME,
PLACE = :PLACE,
DOB = :DOB
where
UNAME = :UNAME
";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
obCmd.Parameters.AddWithValue(":FNAME", TextBox4.Text);
obCmd.Parameters.AddWithValue(":LNAME", TextBox5.Text);
obCmd.Parameters.AddWithValue(":PLACE", TextBox6.Text);
obCmd.Parameters.AddWithValue(":DOB", TextBox7.Text);
obCmd.Parameters.AddWithValue(":UNAME", Label1.Text);
OleDbDataReader obReader = obCmd.ExecuteReader();
For Oracle the : should indicate a parameter (it's a # for Sybase and MS SQL). I named all params like the target columns, but you can use other names of course.