/// <summary>
/// 获取链接
/// </summary>
/// <param name="MYorSqlServer">0 sqlserver ,1 mysql</param>
/// <returns></returns>
public IDbConnection DALBaseConn( )
{
IDbConnection conn = null;
ServerSet linkModel = new ServerSet();
linkModel = JsonToIni.GetClass<ServerSet>(ConfigFiles.ConfigFile);
if (linkModel != null)
{
string defaultcon = "";
defaultcon = $"Data Source ={linkModel.DBAdd}; Initial Catalog ={linkModel.DBName}; User Id = {linkModel.DBUser}; Password ={linkModel.DBPwd}";
try
{
conn = new SqlConnection(defaultcon);
conn.Open();
}
catch (Exception ex)
{
string ErrMsg = string.Format("sql数据库连接错误,错误原因是:{0}", ex.Message);
Common.LogWrite.WriteLog(ErrMsg);
conn = null;
//throw new Exception(ErrMsg);
}
}
return conn;
}
不做解释。。。
其他程序使用方法是:
public ResultMsg Insert(SBRecordMain model)
{
ResultMsg msg = new ResultMsg();
using (IDbConnection conn = new DALBase().DALBaseConn())
{
IDbTransaction transaction = conn.BeginTransaction();
try
{
string sql = $@"
DECLARE @SBIdIn int;
IF Not EXISTS(select 1 from SBInfo where Name =@Name)
begin
insert into [SBInfo] ([Name],[SBType],[SBNo],[IsUsed],[Remark],[CreateDate],[Updated] ) values (@Name,'流量计','',1,'采集数据',getdate(),getdate());
set @SBIdIn= @@IDENTITY; ---获取插入的数据ID
end
else
begin
select @SBIdIn=Id from SBInfo where Name =@Name
end
INSERT [SBRecordMain](
[Name],
[SBType],
[SBNo],
SBId,
[RecordCount],
[Dianya],
[XinhaoZhiliang],
[Remark],
[CreateDate]
)VALUES(
@Name,
@SBType,
@SBNo,
@SBIdIn,
@RecordCount,
@Dianya,
@XinhaoZhiliang,
@Remark,
getdate());
SELECT @@IDENTITY";
msg.ReturnInt = conn.ExecuteScalar<int>(sql, model, transaction);
msg.Success = true;
if (model.ListMX != null)
{
model.ListMX.ForEach(x => x.MainInfoId = msg.ReturnInt);
new DALSBRecordMx().UpdateAll(model.ListMX, transaction, conn);
}
transaction.Commit();//提交事务
msg.Success = true;
}
catch (Exception ex)
{
if (transaction != null)
{
transaction.Rollback();
}
msg.Success = false;
msg.ErrMsg = ex.Message;
}
}
return msg;
}
查询:
/// <summary>
/// 获取1000数据
/// </summary>
/// <param name="Model">SBRecordMain</param>
/// <returns></returns>
public IEnumerable<SBRecordMain> QueryList(string where)
{
using (IDbConnection conn = new DALBase().DALBaseConn())
{
try
{
string sql = $@"select top 1000 * from SBRecordMain where 1=1 {where} order by CreateDate desc ";
return conn.Query<SBRecordMain>(sql);
}
catch (Exception ex)
{
return null;
}
}
}