Losing info when using update query c# - c#

Hi I'm trying to use the update query to update a column or even a whole row, however when I only update a certain column i get "no value given for one or more required parameters". how can i use the code for both updating column and row also?
here's my code:
protected void updateButtn_Click(object sender, EventArgs e)
{
using (var myConnection = GetConnection())
{
myConnection.Open();
// You should be using a parameterized query here
using (var cmd = new OleDbCommand("Update client set username = ?, [name] = ?, surname = ?, [email] = ?, [password] = ? where id = ?", myConnection))
{
cmd.Parameters.AddWithValue("username", txt_uname.Text);
cmd.Parameters.AddWithValue("[name]", txt_name.Text);
cmd.Parameters.AddWithValue("surname", txt_sname.Text);
cmd.Parameters.AddWithValue("[email]", txt_email.Text);
cmd.Parameters.AddWithValue("[password]", txt_password.Text);
cmd.Parameters.AddWithValue("[id]", txt_id.Text);
cmd.ExecuteNonQuery();
} myConnection.Close();
}
}

You forgot to add a parameter for [health issues], that is the missing column the error is yelling at you about.
protected void clientUpdate_Click(object sender, EventArgs e)
{
using (var myConnection = GetConnection())
{
myConnection.Open();
using (var cmd = new OleDbCommand("Update client set [name] = ?, surname = ?, [date of birth] = ?, [health issues] = ?, [yoga experience] = ?, [email] = ?, [phone number] = ?, [home address] = ?, [password] = ? where id = ?", myConnection))
{
cmd.Parameters.AddWithValue("[name]", txt_name.Text);
cmd.Parameters.AddWithValue("surname", txt_sname.Text);
cmd.Parameters.AddWithValue("[date of birth]", txt_dob.Text);
cmd.Parameters.AddWithValue("[health issues]", txt_HealthIssues.Text); \\ <---- This was missing.
cmd.Parameters.AddWithValue("[yoga experience]", txt_exp.Text);
cmd.Parameters.AddWithValue("[email]", txt_email.Text);
cmd.Parameters.AddWithValue("[phone number]", txt_phone.Text);
cmd.Parameters.AddWithValue("[home address]", txt_address.Text);
cmd.Parameters.AddWithValue("[password]", txt_password.Text);
cmd.Parameters.AddWithValue("id", txt_id.Text);
cmd.ExecuteNonQuery();
}
}
}
If you want to only update 1 column you need to write a new query that does not include the other parameters in the query. Traditionally people will use a ORM library like Entity Framework to make this easier to do. You will need to check and see if you can find a ORM library that is compatible with your OleDb connection objects.
Also, if you do not go with a ORM you may want to not use AddWithValue, it has to make assumptions about what datatypes your code is and you can sometimes get large performance problems due to indexes not being used correctly when it guesses wrong.

The problem is that if one of those text boxes is empty, you're supplying a null value as a parameter. That's why you are getting the no value given error.
You can solve this problem by doing:
cmd.Parameters.AddWithValue("[name]", string.IsNullOrEmpty(txt_name.Text) ?
(object)DBNull.Value : txt_name.Text);
This will set the column value to null if the textbox is empty.
You could do something like this if you want to only update fields that have been filled out:
string cmd = "update blah set ";
bool shouldUpdate = false;
if (!string.IsNullOrEmpty(name_textbox))
{
shouldUpdate = true;
cmd += "name = ?,"; don't add the comma for the last one
command.Parameters.AddWithValue("name",name_textbox.Text);
}
... do this for each of your text boxes
if (shouldUpdate)
{
cmd += "where id = ?";
command.Parameters.AddWithValue("id",id);
command.ExecuteNonQuery();
}
but that is kinda ugly and I would recommend making sure the textboxes are populated with the current data when you're loading the page.

Related

How to solve this query Error

How can I get this query to work? keep getting this error:
"syntax error in INSERT INTO statement"
I am confused as it used to work on another program, but I got all scrambled up with this one.
string item = listView1.Items[listView1.FocusedItem.Index].Text;
MessageBox.Show(item); //test Value
string thisDay1 = DateTime.Now.ToString();
ad.InsertCommand = new OleDbCommand("INSERT INTO Scrap-Rework Master Data (Is_today, S_Line, Status, T_Number, Test_Cp, think_a, Rew_Hos, QAffect, Comments)
values (?, ?, ?, ?, ?, ?, ?, ?, ?)", con);
ad.InsertCommand.Parameters.AddWithValue("#S_Line", OleDbType.VarChar).Value = textBox1.Text;
ad.InsertCommand.Parameters.AddWithValue("#Status", OleDbType.VarChar).Value = domainUpDown1.Text;
ad.InsertCommand.Parameters.AddWithValue("#T_Number", OleDbType.VarChar).Value = textBox2.Text;
ad.InsertCommand.Parameters.AddWithValue("#Test_Cp", OleDbType.VarChar).Value = item;
ad.InsertCommand.Parameters.AddWithValue("#think_a", OleDbType.VarChar).Value = domainUpDown2.Text;
ad.InsertCommand.Parameters.AddWithValue("#Rew_Hos", OleDbType.Numeric).Value = Double.Parse(textBox4.Text);
ad.InsertCommand.Parameters.AddWithValue("#QAffect", OleDbType.Numeric).Value = int.Parse(textBox3.Text);
ad.InsertCommand.Parameters.AddWithValue("#Comments", OleDbType.VarChar).Value = textBox5.Text;
ad.InsertCommand.Parameters.AddWithValue("#Is_today", OleDbType.DBTime).Value = thisDay1;
Listview has 2 columns:
ListViewItem listitem = new ListViewItem(dr["Test_Cp"].ToString());
listitem.SubItems.Add(dr["Description"].ToString());
fields on access database and type:
S_Line -Short Text;
Status -Short Text;
T_Number -Short Text;
Test_Cp -Short Text;
think_a -Short Text;
Rew_Hos -Number;
QAffect -Number;
Comments -Long Text;
Is_today -Date/Time;
Thank you so much in advance.
First you must use brackets [] always for the name that contains spaces in query like [Scrap-Rework Master Data].
2- Declare OleDbCommand parameter.
3- Put name of Parameters in query with respect order.
4- Format DateTime field.
5- add cmd.ExecuteNonQuery(); for insert data.
string item = listView1.Items[listView1.FocusedItem.Index].Text;
MessageBox.Show(item); //test Value
OleDbCommand cmd = new OleDbCommand("INSERT INTO [Scrap-Rework Master Data] (S_Line, Status, T_Number, Test_Cp, think_a, Rew_Hos, QAffect, Comments, Is_today)" +
"values(#S_Line, #Status, #T_Number, #Test_Cp, #think_a, #Rew_Hos, #QAffect, #Comments, #Is_today)", con);
cmd.Parameters.AddWithValue("#S_Line", textBox1.Text);
cmd.Parameters.AddWithValue("#Status", domainUpDown1.Text);
cmd.Parameters.AddWithValue("#T_Number", textBox2.Text);
cmd.Parameters.AddWithValue("#Test_Cp", item) ;
cmd.Parameters.AddWithValue("#think_a", domainUpDown2.Text);
cmd.Parameters.AddWithValue("#Rew_Hos", Double.Parse(textBox4.Text)) ;
cmd.Parameters.AddWithValue("#QAffect", int.Parse(textBox3.Text)) ;
cmd.Parameters.AddWithValue("#Comments", textBox5.Text) ;
cmd.Parameters.AddWithValue("#Is_today", DateTime.Now.ToString("#yyyy/MM/dd#"));
cmd.ExecuteNonQuery();
You're using OleDB, so you can't use named parameters:
System.Data.OleDb
Uses positional parameter markers indicated by a question mark (?).
which means (from same page)
As a result, the order in which Parameter objects are added to the Parameters collection must directly correspond to the position of the ? placeholder for the parameter.
The problem is your order is wrong: the first value in your INSERT is Is_Today, but that's the last value you add to the parameter array. Hence all the value types are wrong. Try moving
ad.InsertCommand.Parameters.AddWithValue("#Is_today", OleDbType.DBTime).Value = thisDay1;
to the head of your parameter add list.
Also I agree with abrown's comment: you'll likely need to bracket the table name [Scrap-Rework Master Data] since it has spaces and a dash in it.
Try to use stored procedure in DB:
using (var command1 = new SqlCommand("InsertData", conn)
{
CommandType = CommandType.StoredProcedure
})
{
command1.Parameters.Add("#a1", SqlDbType.Text).Value = A1;
command1.Parameters.Add("#a2", SqlDbType.Text).Value = A2;
command1.Parameters.Add("#a3", SqlDbType.Text).Value = A3;
command1.Parameters.Add("#a4", SqlDbType.Text).Value = A4;
command1.ExecuteNonQuery();
}

Exception while inserting C# datatable into Access table - System.InvalidOperationException: Missing the DataColumn 'ID' for the SourceColumn 'ID'

I am getting the aforementioned exception when I am trying to insert all the rows from my table that has a primary key value on a string column "MedName", into an Access table that has an auto-incremented primary key. This is what I am doing:
OleDbConnection con;
OleDbCommand cmd;
OleDbDataAdapter adapter;
string Connection ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Directory;
con=new OleDbConnection(Connection);
string selectCommand = "select * from AccessTableTest";
cmd=new System.Data.OleDb.OleDbCommand(Query,con) ;
adapter=new OleDbDataAdapter(cmd);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
dt.PrimaryKey = null; //Tried to see if PK is causing trouble. No luck
foreach (DataRow dr in dt.Rows)
{
dr.SetModified(); //Tried this. Helped me to insert for the very first time.
}
adapter.InsertCommand = builder.GetInsertCommand();
var rows = adapter.Update(dt); //dt is the function parameter
con.Close();
SO, adapter.Update(dt) throws error "Missing the DataColumn 'ID' for the SourceColumn 'ID'"
Note: The very first insert command was successful with dr.SetModified() statement but all the subsequent inserts fail. I made sure that all columns of table match with those of access table.
Also, the insert command from adapter.InsertCommand looks like this:
INSERT INTO DrugAudit (Category, SubCategory, Quantity, MedName, OrderTrigger, Issues, Price, Notes, Summary, Recommendations, Alternative)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Please help. I have been trying to resolve this for couple of days now. Thanks!
I resolved the issue by simply looping through the table like this:
con.Open();
foreach (DataRow dr in dt.Rows)
{
string insertCommand = "Insert INTO DrugAudit (Category, SubCategory, Quantity, MedName, OrderTrigger, Issues, Price, Notes, Summary, Recommendations, Alternative) VALUES (";
//dr.SetModified();
foreach (DataColumn dc in dt.Columns)
{
insertCommand += "'" + dr[dc].ToString() + "',"
}
int lastIndex = insertCommand.LastIndexOf(',');
insertCommand = insertCommand.Remove(lastIndex);
insertCommand += ");";
cmd=new System.Data.OleDb.OleDbCommand(insertCommand,con);
int i = cmd.ExecuteNonQuery();
}
But, I would still like to know why adapter.Update(dt) method which I first tried failed to insert table into the access table. Would really appreciate if anyone could point to what I was doing wrong in previous procedure. Thanks!
Inserting the whole table failed, because one of the column names is a reserved keyword.
this requires to specify both QuotePrefix and QuoteSuffix on OleDbCommandBuilder.
For MS access, this is
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
set them before calling GetInsertCommand(), and it should work.

Syntax error in UPDATE statement OleDbException

I'm writing an application which stores user information. Currently the user is supposed to update their Name, Height, Weight and Birthday.
string height = TB_ClientHeight.Text;
string weight = TB_ClientWeight.Text;
string name = TB_ClientName.Text;
string bday = dateTimePicker1.Value.ToString("dd-MM-yyyy");
int heightint = Convert.ToInt32(height);
int weightint = Convert.ToInt32(weight);
It's updated by calling the public static string username variable from another form and using that as the WHERE UserName = #username.
usernamestringo = Login.usernameFromLogin;
I've followed other SO answers in this context and corrected some issues (like preventing SQL Injection). However I'm still getting a syntax error while updating these fields as claimed by OleDbException.
using (OleDbConnection myCon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=O:\Repos\Database\Database.accdb;Persist Security Info=False"))
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
string query = "UPDATE TPersons SET Name=#Name, SET Height=#Height, SET Weight=#Weight, SET Bday=#Bday " + " WHERE FirstName= #username";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Name", name.ToString());
cmd.Parameters.AddWithValue("#Height", heightint.ToString());
cmd.Parameters.AddWithValue("#Weight", weightint.ToString());
cmd.Parameters.AddWithValue("#Bday", bday.ToString());
cmd.Parameters.AddWithValue("#username", usernamestringo);
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Updated!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
cmd.Parameters.Clear();
}
The OleDbException is:
Index #0
NativeError: -526847407
Source: Microsoft Access Database Engine
SQLState: 3000
Description (message): Syntax error in UPDATE statement.
Could anyone guide me where my syntax is wrong? Thank you!
The UPDATE syntax is
UPDATE <tablename> SET field1=Value1, field2=Value2 WHERE primarykeyname=Value3
The SET keyword precedes only the first column to update, and you have another problem with the NAME column. In Access this is a reserved keyword. Use brackets around that column name (or better change it to something not so troublesome)
So:
string query = #"UPDATE TPersons SET [Name]=#Name,
Height=#Height, Weight=#Weight, Bday=#Bday
WHERE FirstName= #username";
Not strictly related to your current problem, but you should look also at this article Can we stop using AddWithValue already? The DbCommand.AddWithValue is a shortcut with numerous drawbacks. Better avoid it.

DataAdapter.UpdateCommand not working c#?

I am using this code to update "SOME" columns in a table in my database. But everytime I try to do so an error is given.
No value given for one or more required parameters.
con.Open();
SlipDA = new OleDbDataAdapter();
string sqlUpdate = "Update tbl_Slip SET RaiseBasic=#RaiseBasic, OtherDed=#OtherDed, Arrears=#Arrears, Notes=#Notes WHERE SlipNo=#SlipNo";
SlipDA.UpdateCommand = new OleDbCommand(sqlUpdate, con);
SlipDA.UpdateCommand.Parameters.AddWithValue("#RaiseBasic", Convert.ToInt32(dRow[4].ToString()));
SlipDA.UpdateCommand.Parameters.AddWithValue("#OtherDed", Convert.ToInt32(dRow[5].ToString()));
SlipDA.UpdateCommand.Parameters.AddWithValue("#Arrears", Convert.ToInt32(dRow[7].ToString()));
SlipDA.UpdateCommand.Parameters.AddWithValue("#Notes", dRow[8].ToString());
SlipDA.UpdateCommand.Parameters.AddWithValue("#SlipNo", dRow[0].ToString());
SlipDA.UpdateCommand.ExecuteNonQuery();
con.Close();
The table contains 9 columns but I only want to update a few.
This Could be the problem :
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example: SELECT * FROM
Customers WHERE CustomerID = ?
source : this
so basically your query should be like this :
string sqlUpdate = "Update tbl_Slip SET RaiseBasic= ?, OtherDed= ?, Arrears= ?, Notes= ? WHERE SlipNo= ?";
try this
string sqlUpdate = "Update tbl_Slip SET RaiseBasic=#RaiseBasic, OtherDed=#OtherDed, Arrears=#Arrears, Notes=#Notes WHERE SlipNo=#SlipNo";
OleDbCommand UpdateCommand = new OleDbCommand(sqlUpdate, con);
UpdateCommand.Parameters.AddWithValue("#RaiseBasic", Convert.ToInt32(dRow[4].ToString()));
UpdateCommand.Parameters.AddWithValue("#OtherDed", Convert.ToInt32(dRow[5].ToString()));
UpdateCommand.Parameters.AddWithValue("#Arrears", Convert.ToInt32(dRow[7].ToString()));
UpdateCommand.Parameters.AddWithValue("#Notes", dRow[8].ToString());
UpdateCommand.Parameters.AddWithValue("#SlipNo", dRow[0].ToString());
con.Open();
UpdateCommand.ExecuteNonQuery();
con.Close();

how do i update data in access database using c# 2010

OleDbConnection vcon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\SummerJob\DataBase.accdb");
string cmdtxt = "UPDATE Students SET S_Name = ?, S_Surname = ?, S_E-Mail = ? WHERE ID = ?";
OleDbCommand cmd = new OleDbCommand(cmdtxt, vcon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("S_Name", EditName.Text);
cmd.Parameters.AddWithValue("S_Surname", editSurname.Text);
cmd.Parameters.AddWithValue("S_E-Mail", editMail.Text);
vcon.Open();
cmd.ExecuteNonQuery();
vcon.Close();
//i use this code but it says syntax error in update statement
Where is the last parameter ???
ID=?
Not sure, but I will bet that without that parameter your query doesn't look right to the parser.
You need to pass ID? via SqlParameter like this cmd.Parameters.AddWithValue("ID", Id.Text);
Also make sure that the parameters are added in the same order they occur

Categories