c# Database update and insert
Im hav开发者_高级运维ing a databse with some customer information (customer_nr(primary key), name, address and so on)
The informaton comes from an xml file and is stored in the databse called customer_info. Now i want to update this table, example if the customer changes his address i want to update the table or, if an customer does not exist i want to insert a new row with the information. Now how do I do this? Ive tried alot of diffrent things but nothing seems to work.
example code:
my insert looks like this:
using (var cmd = new SqlCommand("insert into [customer_info] (custoner_nr, firstName,lastName, adress_1....(and so on))", connection)) {
cmd.Parameters.AddWithValue("@customer_nr", customerNr);
cmd.Parameters.AddWithValue("@firstName", fName);
cmd.Parameters.AddWithValue("@lastName", lName);
cmd.ExecuteNonQuery();
my update looks like this:
using (var cmd = new SqlCommand("UPDATE [customer_info] SET [customer_nr] = @customer_nr [firstName] = @firstName, [lastName] = @lastName, WHERE (([customer_nr] = @customer_nr))", connection)) {
cmd.Parameters.AddWithValue("@custmer_nr", customerNr);
cmd.Parameters.AddWithValue("@fornamn", fName);
cmd.Parameters.AddWithValue("@efternamn", lName);
cmd.ExecuteNonQuery();
I've tried to match the customer_nr
, something like this:
DataRow row = dataSet.custmer_info.FindBycustomer_nr(t.customerNr);
if (bla != null) {
updateCustomer(t.kontoNr,t.fName,t.lastname....);
} else {
insertCustomer(t.kontoNr,t.fName,t.lastname....);
}
If someone understands my problem and could help me i would be so greatful, im really stuck and what ive been testing does not work. =(
As far as i can see you are not opening an closing the connection
using (var cmd = new SqlCommand("UPDATE [customer_info] SET [customer_nr] = @customer_nr [firstName] = @firstName, [lastName] = @lastName, WHERE (([customer_nr] = @customer_nr))", connection)) {
cmd.Parameters.AddWithValue("@custmer_nr", customerNr);
cmd.Parameters.AddWithValue("@fornamn", fName);
cmd.Parameters.AddWithValue("@efternamn", lName);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
you should try using an O/RM tool such as EntityFramework. you can get started here
精彩评论