1. 将SQLhepler添加进来,命名空间导进来。
using Microsoft.ApplicationBlocks.Data;
2. 做连接类DBconnection:
public class DBconnection
{
static string str = "server=.;database=mydb;uid=sa;pwd=901004";
public static SqlConnection Connection ()
{
SqlConnection Conn = new SqlConnection(str);
return Conn;
}
}
3. 做实体类如Info类:
public class Info
{
public string Code{ get; set; }
public string Name { get; set; }
public bool Sex { get; set; }
public string Nation { get; set; }
public DateTime Birthday { get; set; }
}
4. 做数据访问类:
添加数据:利用SqlHelper.ExecuteNonQuery()的重载,将需要的参数传进去。
public class InfoDA
{
public void Add(string code,string name,bool sex,string nation,DateTime birthday)
{
SqlParameter p_code = new SqlParameter("@code", code);
SqlParameter p_name = new SqlParameter("@name", name);
SqlParameter p_sex = new SqlParameter("@sex",sex);
SqlParameter p_nation = new SqlParameter("@nation",nation);
SqlParameter p_birthday = new SqlParameter("@birthday",birthday); SqlHelper.ExecuteNonQuery(DBconnection.Connection(), CommandType.Text, "insert into info values(@code,@name,@sex,@nation,@birthday) ",p_code,p_name,p_sex,p_nation,p_birthday); }
}
查询数据:利用SqlHelper.ExecuteReader()重载,将需要的数据传进去。
public List<Info> Select()
{
List<Info> list = new List<Info>(); SqlDataReader DR = SqlHelper.ExecuteReader(DBconnection.Connection(), CommandType.Text, "select * from info"); while (DR.Read())
{
Info data = new Info();
data.Code = DR["code"].ToString();
data.Name = DR["name"].ToString();
data.Sex = (bool)DR["sex"];
data.Nation = DR["nation"].ToString();
data.Birthday = (DateTime)DR["birthday"];
list.Add(data);
}
return list;
}
5. 在主函数中使用:
InfoDA da = new InfoDA();
List<Info> list = da.Select();
SQLhelper网盘地址:
http://pan.baidu.com/s/1bn913rD