.net三层架构开发步骤
City城市表,id ,name,password,address,phone;
1.新建一个windows窗体应用程序,CitySys
2.文件–》添加–》新建项目–》类库(CitySysModel)–》重命名class1.cs的类(CityModel)。
3.根据数据表里面的字段,在Model里面创建字段。prop+tab
+tab.
eg:public int Id{get;set;}
public string Name{get;set;}
public string Password{get;set;}
public string Address{get;set;}
public string Phone{get;set;}
4.创建DLL层,CitySysDLL。–>重命名Class1.cs,CityDLL。
5.创建BLL层,CitySysBLL。–》重命名Class1.cs,CityBLL。
6.添加引用:表示层引用–》Model层和BLL层
BLL层引用DLL层和MOdel层
DLL层引用Model层
7.去DLL层里面写两个方法(登陆[Login]和AddCity[添加])。
8.DLL层里面的代码:
public string constr = "数据库连接字符串";
//登陆
public bool Login(string name,string password){
string sql = "select * from city where name = @name and password = @password";
SqlParameter [] param = new Sqlparameter[]{new Sqlparameter("@name",name),new SqlParameter("@password",password)};
using(SqlConnection conn = new SqlConnection(constr)){
SqlCommand cmd = new SqlCommand (sql,conn);
cmd.Parameters.AddRange(param);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read()){
dr.Close();
conn.Close();
return true;
}else{
dr.Close();
conn.Close();
return false;
}
}
}
//添加的方法
public int AddCity(City city ){
string sql="insert into city values(@name,@password,@address,@phone)";
SqlParameter [] param = new Sqlparameter[]{
new Sqlparameter("@name",city.name),
new SqlParameter("@password",city.password),
new SqlParameter("@address",city.address),
new SqlParameter("@phone",city.phone)
};
using(SqlConnection conn = new SqlConnection(constr)){
SqlCommand cmd = new SqlCommand(sql,conn);
cmd.Parameters.AddRange(param );
conn.Open();
return cmd.ExecuteNonQuery();
}
}
9.写BLL层。给BLL层里面写登陆的方法和添加的方法
public CityDLL cdll = new CityDLL();
//登陆
public bool Login(string name ,string password){
return cdll.Login(name,password);
}
//添加
public int AddCity(City city){
return cdll.AddCity(city);
}
10.开始在默认的窗体里面拉几个lable和button
label = 欢迎进入某某系统
lable2 = 名称 textbox = Name
lable3 = 密码 textbox = Password
button1 = 登陆 button2 = 取消
11.双击登陆进去。写登陆的方法
public CityBLL cbll = new CityBLL();
//获取值
string name = this.Name.Text;
string password = this.Password.Text;
if(cbll.Login(name,password)){
MessageBox.Show("登陆成功");
FrmMain fm = new FrmMain();
fm.Show();
this.Hide();
} else{
MessageBox.Show("登陆失败");
}
12.创建一个主窗体,右击–》添加–》windows窗体–》FrmMain.–》拉四个Button,分别是添加信息,查询信息,修改信息,删除信息
13.双击添加信息进去,写代码:
//打开添加的窗体
addCity ac = new addcity();
ac.Show();
this.Hide();
14.拉一个添加的窗体。双击添加按钮进去写代码:
//获取值
City city = new City();
city.Name = this.name.Text;
city.Password = this.Password.Text;
city.Address = this.Address.Text;
city.Phone = this.Phone.Text;
//调用bll里面添加方法
int rel = cbll.AddCity(city);
if(rel>0){
MessageBox.Show("添加成功");
}else{
MessageBox.Show("添加失败");
}