Little Experience in passing parameters when executing SQL statements in C #
Source: Internet
Author: User
In C #, it is inevitable to use various SQL statements to deal with databases, and passing parameters to SQL statements is also inevitable. The following is my summary (do not laugh ):
1> direct writing:
For example:
Int id = 1;
String name = "lui ";
Cmd. commandtext = "insert into tuserlogin values (" + ID + ", '" + name + "')";
Because ID is a numeric value, you only need to use "+ ID +" in the SQL string to implement the transfer, while name is a string, therefore, you need to add a single quotation mark (') on both sides of "+ name +" during transmission;
2> Add the parameter method to the command object:
For example:
Int id = 1;
String name = "lui ";
Cmd. commandtext = "insert into tuserlogin values (@ ID, @ name )";
// Write the added parameter name in the preceding SQL statement, regardless of the parameter type.
Sqlparameter para = new sqlparameter ("@ ID", sqldbtype.int, 4); // generate a parameter named @ ID, which must start with @ to indicate the added parameter, set the type length. The type length is the same as that of the corresponding field in the database.
Para. value = ID; // assign a value to the parameter
Cmd. Parameters. Add (para); // you must add the parameter variables to the command object.
// The following is similar
Para = new sqlparameter ("@ name", sqldbtype. varchar, 16 );
Para. value = Name;
Com. Parameters. Add (para );
... Then you can perform database operations.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.