using SqlData=System.Data.SqlClient.SqlDataAdapter
//连接字段
private static string strConn =
ConfigurationManager.ConnectionStrings
["sql"]. ConnectionString:
//查询
public static DataTable Query(string sql,params SqlParameter)
{
using (SqlDataAdapter adt=new Sq1DataAdapter(sql, strConn))
{
if(SqlParameters!=null&&SqlParameters.count>0)
adapter.selectcommand.SqlParameters.addrange(SqlParameters);
using (DataTable dt = new DataTable())
{
adapter. Fill(dt) ;
return dt;
}
}
}
public static SqlDataReader QueryReader(string sql,params SqlParameter[] SqlParameters)
{
using (Sq1Connection sq1Connection = new Sq1Connect ion(strConn))
{
using (Sq1Command sq1Command = new Sq1Command (sq1,sqlConnection))
{
if(SqlParameters!=null&&SqlParameters.count>0)
adapter.selectcommand.SqlParameters.addrange(SqlParameters);
sqlConnection. Open();
return sq1Command. ExecuteReader(CommandBehavior.CloseConnection) ;
}
}
}
DAL层
public static userinfo select(string name,string pwd)
{
//构建查询语句 = 不能like
var sql=$"select * from userinfo where name=@name and pwd=@pwd";
SqlParameter[] SqlParameter={
new SqlParameter("@name",name),
new SqlParameter("@pwd",pwd),
}
var reader=SqlHelper.QueryReader(sql,sqlParameter);
reader.Close();
if(reader.Read())
{
userinfo user=new userinfo()
{
id=convert.ToInt32(row["id"]),
name=convert.ToString(row["name"]),
role=convert.ToInt32(row["role"])
};
reader.Close();
return user;
}
else{
reader.Close();
return null;
}
var dt=DBHelper.Query(sql, SqlParameter);
//如果没有数据 null
if (dt == null || dt.Rows.Count<1)
{
return null;
}
//如果有数据,取第一行,转换为对象
var row=dt.rows[0];
userinfo user=new userinfo()
{
id=convert.ToInt32(row["id"]),
name=convert.ToString(row["name"]),
role=convert.ToInt32(row["role"])
};