使用最简单的方式进行对数据库访问,并且查询返回需要的数据;如下步骤:
一、web.config 配置
<connectionStrings>
<add name="ABConnection" connectionString="Data Source=.;Initial Catalog=xx_Db;User ID=xx;Password=789xxxxxxx;" providerName="System.Data.SqlClient" />
<add name="AB2Connection" connectionString="Data Source=.;Initial Catalog=xxx_Db; User ID=sa;Password=789xxxxxxx;" providerName="System.Data.SqlClient" />
</connectionStrings>
二、Entity
namespace xx.Entity
{
public class Entity : DbContext
{
public virtual DbSet<User> Users { get; set; }
public ScrmEntity() : base("name=AB2Connection"){ }
}
}
三、Model User 的模型
四、sqlHelp 通过sql 获取数据库查询数据
public class sqlHelper
{
public static List<T> QueryList<T>(string sql, params SqlParameter[] para )
{
string connStr = ConfigurationManager.ConnectionStrings["AB2Connection"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
SqlCommand comm = new SqlCommand(sql, conn);
comm.Parameters.AddRange(para);
conn.Open();
var reader= comm.ExecuteReader();
List<T> DataList = new List<T>();
while (reader.Read())
{
T RowInstance = Activator.CreateInstance<T>();//动态创建数据实体对象
//通过反射取得对象所有的Property
foreach (PropertyInfo Property in typeof(T).GetProperties())
{
try
{
//取得当前数据库字段的顺序
int Ordinal = reader.GetOrdinal(Property.Name);
if (reader.GetValue(Ordinal) != DBNull.Value)
{
var ptype = Property.PropertyType;
var pvalue = reader.GetValue(Ordinal);
var ppvalue = Convert.ChangeType(pvalue, ptype);
//将DataReader读取出来的数据填充到对象实体的属性里
Property.SetValue(RowInstance, ppvalue, null);
}
}
catch
{
break;
}
}
DataList.Add(RowInstance);
}
return DataList;
}
五、xxController
string sql = "select Password from xxTable.Users where [email protected]";
//构建参数
SqlParameter[] pms = new SqlParameter[]
{
new SqlParameter("@loginId",SqlDbType.VarChar,50){ Value =user.userName},
};
var hashPassword = sqlHelper.ExecuteScalar(sql, pms);
原文地址:https://www.cnblogs.com/llw1996/p/11405319.html