Copy codeThe Code is as follows:
Public bool Add (Liuyan refmodel)
{
String SQL = "insert into liuyan (name, phone, zhiwei, gongsi, addr, country, dianyou, content, adddate) values (@ name, @ phone, @ zhiwei, @ gongsi, @ addr, @ country, @ dianyou, @ content, @ adddate )";
OleDbParameter [] parameters = {
New OleDbParameter ("@ name", OleDbType. VarChar ),
New OleDbParameter ("@ tel", OleDbType. VarChar ),
New OleDbParameter ("@ zhiwei", OleDbType. VarChar ),
New OleDbParameter ("@ gongsi", OleDbType. VarChar ),
New OleDbParameter ("@ addr", OleDbType. VarChar ),
New OleDbParameter ("@ country", OleDbType. VarChar ),
New OleDbParameter ("@ dianyou", OleDbType. VarChar ),
New OleDbParameter ("@ content", OleDbType. VarChar ),
New OleDbParameter ("@ adddate", OleDbType. VarChar)
};
Parameters [0]. Value = model. Xingming;
Parameters [1]. Value = model. Tel;
Parameters [2]. Value = model. Zhiwei;
Parameters [3]. Value = model. Gongsi;
Parameters [4]. Value = model. Addr;
Parameters [5]. Value = model. Country;
Parameters [6]. Value = model. Dianyou;
Parameters [7]. Value = model. Content;
Parameters [8]. Value = model. Adddate;
Return sqlHelper.exe cuteCommand (SQL, parameters );
}
This article describes the reflection. Now we will talk about the position in the Code where reflection is used. It's just a whimsy to save effort in the coding process.
Copy codeThe Code is as follows:
Parameters [0]. Value = model. Xingming;
Parameters [1]. Value = model. Tel;
Parameters [2]. Value = model. Zhiwei;
Parameters [3]. Value = model. Gongsi;
Parameters [4]. Value = model. Addr;
Parameters [5]. Value = model. Country;
Parameters [6]. Value = model. Dianyou;
Parameters [7]. Value = model. Content;
Parameters [8]. Value = model. Adddate;
When there are many attributes in the class, the above Code can use reflection to assign values.
Copy codeThe Code is as follows:
// Use Reflection to reference using System. Reflection; namespace
Type t = refmodel. GetType ();
For (int I = 0; I <t. GetProperties (). Length; I ++)
{
Parameters [I]. Value = t. GetProperties () [I]. GetValue (refmodel, null );
}
Reflection is used to obtain all attributes of the class.
Then, traverse the property and assign the property value to the parameter.
Of course, the added method does not have model. Id.
Therefore, the for loop starts from 1.
Then, when parameters [I]. Value is assigned, I will subtract a parameters [I-1]. Value.
In this way, when you write a value to the data layer, you do not have to copy and paste the parameters one by one.
How can I share it with you?
You can ignore the code generation tool.