In order to make the code more standardized, so that the interface more beautiful and concise, you need to encapsulate the class.
It is divided into the following steps:
1, build dbconnection, make a constant of the link string
Class DBConnection
{
Public const string Connstring= "server=.; Database=mydb;uid=sa;pwd=123 ";
}
2, create the entity class, the database of the table encapsulation class, the database fields are encapsulated into member variables and attributes
Class Nation
{
private string Code;
public string Code
{
Get{return Code;}
Set{code=value;}
}
private string name;
public string Name
{
Get{return name;}
Set{name=value;}
}
}
3, build data access class
A, declare three members: Sqlconnection,sqlcommand,sqldatareader
B, instantiate the SqlConnection and SqlCommand in the constructor.
C, do a series of additions and deletions to change the method
Class Nationda
{
Private SqlConnection _conn;
Private SqlCommand _cmd;
Private SqlDataReader _dr;
Public stockda ()
{
_conn = new SqlConnection (dbconnection.connstring);
_cmd = _conn. CreateCommand ();
}
public void Insert (string code,string name)
{
}
。。。。。。。。。。。
Public list<nation> Select ()//query multiple data out, put in a list collection, each element in the collection is a Nation object, both have the code and the Name property
{
}
Public Nation Select (string code)//Find out at most one piece of data according to the code query, using a Nation object to receive
{
}
}
4,main function: Interface display
(1) Method of invoking query
A, call the data access class, get the data
List<nation> st=new Nationda (). Select (); Call the Select method in the Nationda class to return a List<nation> object
b, reading the data with A for loop
for (i=0;i<st.count;i++)
{
Console.WriteLine (St[i].code+st[i].name);
}
(2) Call to delete and change the method
A, the input data is obtained from the interface, there are variables in the
b, call the data access class, the variable to the corresponding additions and deletions of the method, to achieve the corresponding operation of the database (first instantiate the class, and then call the method)
Data access--encapsulation class