C# SqlParameter SqlDataAdapter

  • Thread starter Thread starter Jason Huang
  • Start date Start date
J

Jason Huang

Hi,

I want to use the Sqlparameter and SqlDataAdapter to update my data,
and the data will be updated based on two TextBoxes txtCustName and
txtCustAddress.
Thanks for help.

Jason
 
Could you provide a bit more information ...
the following example show how to update a particular customer's data based on
the value of txtCustName and the value of txtCustAddress

//assume there is a SqlConnection called myConnection
SqlCommand myCommand = new SqlCommand("", myConnection);
myCommand.CommandText = "UPDATE Customers SET CustomerData = @Data WHERE
CustomerName = @CusName AND CustomerAddress = @CusAddress";
myCommand.Parameters.Add(new SqlParameter(@CusName, txtCustName.Text);
myCommand.Parameters.Add(new SqlParameter(@CusAddress,
txtCustAddress.Text);
myCommand.Parameters.Add(new SqlParameter(@CusData, txtCustData.Text);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
}

SqlDataAdapter is only used when u update the database from a dataset

cheers,
Ivan
 
@Data should be @CusData

Ivan Wong said:
Could you provide a bit more information ...
the following example show how to update a particular customer's data based on
the value of txtCustName and the value of txtCustAddress

//assume there is a SqlConnection called myConnection
SqlCommand myCommand = new SqlCommand("", myConnection);
myCommand.CommandText = "UPDATE Customers SET CustomerData = @CusData WHERE
CustomerName = @CusName AND CustomerAddress = @CusAddress";
myCommand.Parameters.Add(new SqlParameter(@CusName, txtCustName.Text);
myCommand.Parameters.Add(new SqlParameter(@CusAddress,
txtCustAddress.Text);
myCommand.Parameters.Add(new SqlParameter(@CusData, txtCustData.Text);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
}

SqlDataAdapter is only used when u update the database from a dataset

cheers,
Ivan
 
Thanks Ivan.
I am thinking in the "myCommand.Parameters.Add(new SqlParameter(@CusName,
txtCustName.Text);", do we need to specify the SqlDbType for the CusName
column?
Will that make any difference?

Jason
 
Absolutely, you should specify the sqldbtype for each of the sqlParameter
in the example the sqlDbType of the @CusName is varChar, if the
CustomerName column has a different type then it will throw exception ...

It is always important to specify the type and the precision of the value
in order to avoid sql injection attack.

Hope it helps
Ivan
 
Back
Top