大家可以参考一下 我也是初学者哦 哈哈
==========================================================
namespace DAL
{
public class StudentInfoDAL
{
DBHelper dbHelper = new DBHelper();
public int Student_INS(StudentInfo stu)
{
string strSql = string.Format("insert into StudentInfo(name,sex,age,phone,address,birthday)"
+ "values('{0}','{1}','{2}','{3}','{4}','{5}')", stu.Name,stu.Sex,stu.Age,stu.Phone,stu.Address,stu.Birthday);
int result = 0;
result = dbHelper.ExecuteNonQuery(strSql);
return result;
}
public StudentInfo getStudentInfo(string Name)
{
string strSql = string.Format("select * from StudentInfo where name like '%{0}%'", Name);
DataSet ds = new DataSet();
ds = dbHelper.getDataSet(strSql);
StudentInfo stu = new StudentInfo();
stu.Name = Convert.ToString(ds.Tables[0].Rows[0]["name"]);
stu.Sex = Convert.ToString(ds.Tables[0].Rows[0]["sex"]);
stu.Age = Convert.ToInt32(ds.Tables[0].Rows[0]["age"]);
stu.Phone = Convert.ToString(ds.Tables[0].Rows[0]["phone"]);
stu.Address = Convert.ToString(ds.Tables[0].Rows[0]["address"]);
return stu;
}
public int Student_UPD(StudentInfo stu)
{
string strSql = string.Format("update StudentInfo set age='{0}' where name = '{1}'", stu.Age, stu.Name);
int result = 0;
result = dbHelper.ExecuteNonQuery(strSql);
return result;
}
public int Student_DEL(StudentInfo stu)
{
string strSql = string.Format("delete from StudentInfo where name = '{0}'", stu.Name);
int result = 0;
result = dbHelper.ExecuteNonQuery(strSql);
return result;
}
}
}
============================================================================================
namespace DAL
{
public class DBHelper
{
SqlConnection con = null;
public SqlConnection getConnection()
{
string strCon = "Data Source=.;Initial Catalog=MySchool;Persist Security Info=True;User ID=sa;Password=123";
SqlConnection con = new SqlConnection(strCon);
return con;
}
public int ExecuteNonQuery(string strSql)
{
con = getConnection();
con.Open();
SqlCommand cmd = new SqlCommand(strSql, con);
int result = 0;
result = cmd.ExecuteNonQuery();
con.Close();
return result;
}
public DataSet getDataSet(string strSql)
{
con = getConnection();
con.Open();
SqlCommand cmd = new SqlCommand(strSql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
return ds;
}
}
}