zoukankan      html  css  js  c++  java
  • net core体系-web应用程序-4asp.net core2.0 项目实战(1)-5项目数据库操作封装操作

    本文目录
    1. 摘要
    2. Ado.Net数据库操作封装类 
    3. EF Core数据库操作
    4. 总结

    1.  摘要

      Asp.Net Core2.0下操作MSSQL数据库,这里介绍两种操作方式,一种是.NET Framework的ADO.NET《Ado.Net百科》,另一种就是Net Core2.0下的一种orm操作EF Core,由于本人习惯Ado.Net编程模式,EF Core涉猎不是很深,推荐网友连接,本文有不写的不到之处欢迎大家批评指正。

    2.  Ado.Net数据库操作封装类

      2.1配置文件

        在appsettings.json添加相关配置,配置数据库连接字符串,配置与原来在web.config中基本一致,只是形式略有差异。

     //数据库连接
      "ConnectionStrings": {
        "SqlDSN": "server=.;uid=sa;pwd=123456;database=NCMVC;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=false;"
      }

      2.2SqlParameter参数封装DbParameters类

        以前传sql参数是以下这种,操作不太方便,顺序还不乱,添加修改删除字段代码改动量比较大。

    SqlParameter[] parameters = {
                            new SqlParameter("@id", SqlDbType.NVarChar,32) ,            
                            new SqlParameter("@name", SqlDbType.NVarChar,128)            
                };    
                parameters[0].Value = model.id;                        
                parameters[1].Value = model.name; 

        封装后在使用实例如下,非常方便实用,还不用在意字段类型,所有处理都在封装类中实现。

    DbParameters p = new DbParameters();
    p.Add("@id", model.id);
    p.Add("@name ", model.name);

    DbParameters封装类

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Text;

    namespace NC.Core
    {
    public class DbParameters
    {
    private List<SqlParameter> li;

    //构造函数
    public DbParameters()
    {
    li = new List<SqlParameter>();
    }

    //单个参数的构造函数
    public DbParameters(string strName, object strValue)
    {
    li = new List<SqlParameter>();
    this.Add(strName, strValue);
    }


    #region ** 属性 **
    //长度
    public int Length
    {
    get { return li.Count; }
    }
    //索引
    public SqlParameter this[int k]
    {
    get
    {
    if (li.Contains(li[k]))
    {
    SqlParameter parm = li[k];
    return parm;
    }
    else
    {
    return null;
    }
    }
    }
    #endregion

    #region ** 添加参数
    //添加 Input 类型参数
    public void Add(string sName, object sValue)
    {
    li.Add(new SqlParameter()
    {
    ParameterName = sName.Trim(),
    Value = sValue ?? DBNull.Value,
    Direction = ParameterDirection.Input,
    });
    }
    //添加 Output 类型参数
    public void AddOut()
    {
    AddOut("@Result", "int", 4);
    }
    public void AddOut(string sName, string sDbType, int iSize)
    {
    li.Add(new SqlParameter()
    {
    ParameterName = sName,
    SqlDbType = ConvertSqlDbType(sDbType),
    Size = iSize,
    Direction = ParameterDirection.Output,
    });
    }
    public void AddInputOutput(string sName)
    {
    li.Add(new SqlParameter()
    {
    ParameterName = sName,
    Direction = ParameterDirection.InputOutput,
    });
    }
    public void AddInputOutput(string sName, string sDbType, int iSize)
    {
    li.Add(new SqlParameter()
    {
    ParameterName = sName,
    SqlDbType = ConvertSqlDbType(sDbType),
    Size = iSize,
    Direction = ParameterDirection.InputOutput,
    });
    }
    //输出测试内容
    public void Output()
    {
    //netcore2.0里没有HttpContext后续这里改为日志记录
    //System.Web.HttpContext.Current.Response.Write("参数输出:---- <br />");

    for (int i = 0; i < li.Count; i++)
    {
    SqlParameter p = li[i];
    string pName = p.ParameterName;
    string pVal = Convert.ToString(p.Value);
    //System.Web.HttpContext.Current.Response.Write(pName + " 的值为: " + pVal + " <br />");
    }
    }
    #endregion

    #region ** 参数转换函数
    //SqlDbType数据类型转换
    private SqlDbType ConvertSqlDbType(string strDbType)
    {
    SqlDbType t = new SqlDbType();
    switch (strDbType.Trim().ToLower())
    {
    case "nvarchar": t = SqlDbType.NVarChar; break;
    case "nchar": t = SqlDbType.NChar; break;
    case "varchar": t = SqlDbType.VarChar; break;
    case "char": t = SqlDbType.Char; break;
    case "int": t = SqlDbType.Int; break;
    case "datetime": t = SqlDbType.DateTime; break;
    case "decimal": t = SqlDbType.Decimal; break;
    case "bit": t = SqlDbType.Bit; break;
    case "text": t = SqlDbType.Text; break;
    case "ntext": t = SqlDbType.NText; break;
    case "money": t = SqlDbType.Money; break;
    case "float": t = SqlDbType.Float; break;
    case "binary": t = SqlDbType.Binary; break;
    }
    return t;
    }

    #endregion

    #region ** 清空参数集合
    public void Clear()
    {
    li.Clear();
    }
    #endregion
    }
    }

    2.3数据库连接、增删改查操作

        默认只有一个数据库连接,多个数据库连接的话再添加实例就可以了,注意这个类是从net freamwork下老项目直接修改得来,net core下并非所有的方法都有使用过。  增、删、改、查均是SQL语句的命令,所以只要存在能向数据库发送SQL脚本的接口则可以实现,Command,要发送脚本总要知道脚本往哪里发找到了Connection,执行完脚本数据库向我们回发结果总要有一个承载 Reader、 Record。Asp.Net Core下提供的基础方法如下,参考DbHelper类完善你自己的SqlHelper类吧。

    DbHelper类

    1 using System.Collections.Generic; 2 using Microsoft.Extensions.Logging; 3 using System.Data.SqlClient; 4 using System.Data; 5 using System; 6 using System.Collections; 7 using System.Reflection; 8 9 using NC.Common; 10 namespace NC.Core 11 { 12 public class DbHelper 13 { 14 public static ILogger Log = UtilLogger<DbHelper>.Log;//日志记录 15 16 #region --定义变量-- 17 public string dsn; 18 //默认实例 : DbCommand.SqlDSN.CraeteSqlDataTable(sql, p); 19 public static DbHelper SqlDSN { get { return new DbHelper(); } } 20 21 #endregion 22 23 #region --构造函数-- 24 /// <summary> 25 /// 构造函数 26 /// </summary> 27 public DbHelper() 28 { 29 //dsn = Encrypt.Dec(dsn); //解密 30 //dsn = Configuration.GetConnectionString("SqlDSN"); 31 dsn = UtilConf.GetConnectionString("SqlDSN"); 32 } 33 /// <summary> 34 /// 多数据库 35 /// </summary> 36 /// <param name="strDSN"></param> 37 public DbHelper(string strDSN) 38 { 39 Log.LogInformation(strDSN); 40 //dsn = Configuration.GetConnectionString(strDSN); 41 dsn = UtilConf.GetConnectionString(strDSN); 42 } 43 #endregion 44 45 #region ** 打开/关闭链接 ** 46 /// <summary> 47 /// 打开链接 48 /// </summary> 49 private void ConnOpen(ref SqlCommand comd) 50 { 51 if (comd.Connection.State == ConnectionState.Closed) 52 comd.Connection.Open(); 53 } 54 55 /// <summary> 56 /// 关闭链接 57 /// </summary> 58 private void ConnClose(ref SqlCommand comd) 59 { 60 if (comd.Connection.State == ConnectionState.Open) 61 { 62 comd.Connection.Close(); 63 } 64 comd.Dispose(); 65 } 66 #endregion 67 68 #region ** 创建 SqlCommand 对象 69 /// <summary> 70 /// 生成comd对象 71 /// </summary> 72 public SqlCommand CreateComd(string spName) 73 { 74 try 75 { 76 SqlConnection conn = new SqlConnection(dsn); 77 SqlCommand comd = conn.CreateCommand(); 78 comd.CommandText = spName; 79 comd.CommandType = CommandType.StoredProcedure; 80 81 return comd; 82 } 83 catch (System.Exception ex) 84 { 85 Log.LogError("DbCommand->CreateComd(sp) 出错 " + ex.Message); 86 throw new Exception(ex.Message); 87 } 88 } 89 public SqlCommand CreateComd(string spName, DbParameters p) 90 { 91 try 92 { 93 SqlCommand comd = CreateComd(spName); 94 95 int len = p.Length; 96 if (len > 0) 97 { 98 for (int i = 0; i < len; i++) 99 { 100 comd.Parameters.Add(p[i]); 101 } 102 } 103 return comd; 104 } 105 catch (System.Exception ex) 106 { 107 Log.LogError("DbCommand->CreateComd(sp) 出错 " + ex.Message); 108 throw new Exception(ex.Message); 109 } 110 } 111 public SqlCommand CreateSqlComd(string strSql) 112 { 113 try 114 { 115 SqlConnection conn = new SqlConnection(dsn); 116 SqlCommand comd = conn.CreateCommand(); 117 comd.CommandText = strSql; 118 comd.CommandType = CommandType.Text; 119 120 return comd; 121 } 122 catch (System.Exception ex) 123 { 124 Log.LogError("DbCommand->CreateSqlComd(s) 出错 " + ex.Message); 125 throw new Exception(ex.Message); 126 } 127 } 128 public SqlCommand CreateSqlComd(string strSql, DbParameters p) 129 { 130 try 131 { 132 SqlCommand comd = CreateSqlComd(strSql); 133 134 int len = p.Length; 135 if (len > 0) 136 { 137 for (int i = 0; i < len; i++) 138 { 139 comd.Parameters.Add(p[i]); 140 } 141 } 142 return comd; 143 } 144 catch (System.Exception ex) 145 { 146 Log.LogError("DbCommand->CreateSqlcomd(s,p) 出错 " + ex.Message); 147 throw new Exception(ex.Message); 148 } 149 } 150 #endregion 151 152 #region ** 创建 SqlDataAdapter 对象 153 /// <summary> 154 /// 根据存储过程名,生成SqlDataAdapter对象 155 /// </summary> 156 public SqlDataAdapter CreateAdapter(string spName) 157 { 158 try 159 { 160 SqlConnection conn = new SqlConnection(dsn); 161 SqlDataAdapter comdAdapter = new SqlDataAdapter(spName, conn); 162 comdAdapter.SelectCommand.CommandType = CommandType.StoredProcedure; 163 164 return comdAdapter; 165 } 166 catch (System.Exception ex) 167 { 168 Log.LogError("DbCommand->CreateAdapter(s) 出错 " + ex.Message); 169 throw new Exception(ex.Message); 170 } 171 } 172 /// <summary> 173 /// 根据存储过程名和参数,生成SqlDataAdapter对象 174 /// </summary> 175 public SqlDataAdapter CreateAdapter(string spName, DbParameters p) 176 { 177 try 178 { 179 SqlDataAdapter comdAdapter = CreateAdapter(spName); 180 181 int len = p.Length; 182 if (len > 0) 183 { 184 for (int i = 0; i < len; i++) 185 { 186 comdAdapter.SelectCommand.Parameters.Add(p[i]); 187 } 188 } 189 190 return comdAdapter; 191 } 192 catch (System.Exception ex) 193 { 194 Log.LogError("DbCommand->CreateAdapter(s, p) 出错 " + ex.Message); 195 throw new Exception(ex.Message); 196 } 197 } 198 /// <summary> 199 /// 根据SQL语句,生成DataAdapter对象 200 /// </summary> 201 public SqlDataAdapter CreateSqlAdapter(string strSql) 202 { 203 try 204 { 205 SqlConnection conn = new SqlConnection(dsn); 206 SqlDataAdapter apter = new SqlDataAdapter(strSql, conn); 207 apter.SelectCommand.CommandType = CommandType.Text; 208 209 return apter; 210 } 211 catch (System.Exception ex) 212 { 213 Log.LogError("DbCommand->CreateSqlAdapter(s) 出错 " + ex.Message); 214 throw new Exception(ex.Message); 215 } 216 } 217 /// <summary> 218 /// 根据SQL语句和参数,生成DataAdapter对象 219 /// </summary> 220 public SqlDataAdapter CreateSqlAdapter(string strSql, DbParameters p) 221 { 222 try 223 { 224 SqlDataAdapter apter = CreateSqlAdapter(strSql); 225 226 int len = p.Length; 227 if (len > 0) 228 { 229 for (int i = 0; i < len; i++) 230 { 231 apter.SelectCommand.Parameters.Add(p[i]); 232 } 233 } 234 235 return apter; 236 } 237 catch (System.Exception ex) 238 { 239 Log.LogError("DbCommand->CreateSqlAdapter(s,p) 出错 " + ex.Message); 240 throw new Exception(ex.Message); 241 } 242 } 243 #endregion 244 245 #region ** 创建 DataReader 对象 246 /// <summary> 247 /// 根据存储过程生成生SqlDataReader 248 /// </summary> 249 public SqlDataReader CreateDataReader(string spName) 250 { 251 SqlCommand comd = CreateComd(spName); 252 return GetDataReader(comd); 253 } 254 /// <summary> 255 /// 根据存储过程和参数生成SqlDataReader 256 /// </summary> 257 public SqlDataReader CreateDataReader(string spName, DbParameters p) 258 { 259 SqlCommand comd = CreateComd(spName, p); 260 return GetDataReader(comd); 261 } 262 /// <summary> 263 /// 根据SQL语句生成SqlDataReader 264 /// </summary> 265 public SqlDataReader CreateSqlDataReader(string strSql) 266 { 267 SqlCommand comd = CreateSqlComd(strSql); 268 return GetDataReader(comd); 269 } 270 /// <summary> 271 /// 根据SQL语句和参数生成SqlDataReader 272 /// </summary> 273 public SqlDataReader CreateSqlDataReader(string strSql, DbParameters p) 274 { 275 SqlCommand comd = CreateSqlComd(strSql, p); 276 return GetDataReader(comd); 277 } 278 279 #region - GetDataReader() 280 //获取DataReader 281 private SqlDataReader GetDataReader(SqlCommand comd) 282 { 283 try 284 { 285 ConnOpen(ref comd); 286 return comd.ExecuteReader(CommandBehavior.CloseConnection); 287 } 288 catch (System.Exception ex) 289 { 290 ConnClose(ref comd); 291 Log.LogError("DbCommand->GetDataReader() 出错 " + ex.Message); 292 throw new Exception(ex.Message); 293 } 294 } 295 #endregion 296 #endregion 297 298 299 #region ** 创建 DataTable 对象 300 /// <summary> 301 /// 根据存储过程创建 DataTable 302 /// </summary> 303 public DataTable CreateDataTable(string spName) 304 { 305 SqlDataAdapter adapter = CreateAdapter(spName); 306 return GetDataTable(adapter); 307 } 308 /// <summary> 309 /// 根据存储过程和参数创建 DataTable 310 /// </summary> 311 public DataTable CreateDataTable(string spName, DbParameters p) 312 { 313 SqlDataAdapter adapter = CreateAdapter(spName, p); 314 return GetDataTable(adapter); 315 } 316 /// <summary> 317 /// 根据SQL语句,创建DataTable 318 /// </summary> 319 public DataTable CreateSqlDataTable(string strSql) 320 { 321 SqlDataAdapter adapter = CreateSqlAdapter(strSql); 322 return GetDataTable(adapter); 323 } 324 /// <summary> 325 /// 根据SQL语句和参数,创建DataTable 326 /// </summary> 327 public DataTable CreateSqlDataTable(string strSql, DbParameters p) 328 { 329 SqlDataAdapter adapter = CreateSqlAdapter(strSql, p); 330 return GetDataTable(adapter); 331 } 332 333 #region - GetDataTable() 334 private DataTable GetDataTable(SqlDataAdapter adapter) 335 { 336 try 337 { 338 DataTable dt = new DataTable(); 339 adapter.Fill(dt); 340 341 return dt; 342 } 343 catch (System.Exception ex) 344 { 345 Log.LogError("DbCommand->GetSqlDataTable() 出错 " + ex.Message); 346 throw new Exception(ex.Message); 347 } 348 finally 349 { 350 if (adapter.SelectCommand.Connection.State == ConnectionState.Open) 351 { 352 adapter.SelectCommand.Connection.Close(); 353 } 354 adapter.Dispose(); 355 } 356 } 357 #endregion 358 359 #endregion 360 361 #region ** 创建 Scalar 对象 362 /// <summary> 363 /// 创建无参数的 Scalar 对象 364 /// </summary> 365 public object CreateScalar(string spName) 366 { 367 SqlCommand comd = CreateComd(spName); 368 return GetScalar(comd); 369 } 370 /// <summary> 371 /// 有参数的 Scalar 对象 372 /// </summary> 373 public object CreateScalar(string spName, DbParameters p) 374 { 375 SqlCommand comd = CreateComd(spName, p); 376 return GetScalar(comd); 377 } 378 /// <summary> 379 /// 根据SQL语句,创建Scalar对象 380 /// </summary> 381 public object CreateSqlScalar(string strSql) 382 { 383 SqlCommand comd = CreateSqlComd(strSql); 384 return GetScalar(comd); 385 } 386 /// <summary> 387 /// 根据SQL语句和参数,创建Scalar对象 388 /// </summary> 389 public object CreateSqlScalar(string strSql, DbParameters p) 390 { 391 SqlCommand comd = CreateSqlComd(strSql, p); 392 return GetScalar(comd); 393 } 394 395 #region - GetScalar() 396 private object GetScalar(SqlCommand comd) 397 { 398 try 399 { 400 ConnOpen(ref comd); 401 object o = comd.ExecuteScalar(); 402 ConnClose(ref comd); 403 404 return o; 405 } 406 catch (System.Exception ex) 407 { 408 ConnClose(ref comd); 409 Log.LogError("DbCommand->GetScalar() 出错 " + ex.Message); 410 throw new Exception(ex.Message); 411 } 412 } 413 #endregion 414 #endregion 415 416 #region ** 执行数据库操作 - ToExecute() ** 417 /// <summary> 418 /// 执行数据库操作 419 /// </summary> 420 private int ToExecute(SqlCommand comd) 421 { 422 try 423 { 424 ConnOpen(ref comd); 425 int iOk = comd.ExecuteNonQuery(); 426 ConnClose(ref comd); 427 return iOk; 428 } 429 catch (System.Exception ex) 430 { 431 ConnClose(ref comd); 432 Log.LogError("DbCommand->ToExecute() 出错 " + ex.Message); 433 throw new Exception(ex.Message); 434 } 435 } 436 437 private int ToExecuteInt(SqlCommand comd) 438 { 439 try 440 { 441 ConnOpen(ref comd); 442 int iOk = 0; 443 int.TryParse(comd.ExecuteScalar().ToString(), out iOk); 444 ConnClose(ref comd); 445 return iOk; 446 } 447 catch (System.Exception ex) 448 { 449 ConnClose(ref comd); 450 Log.LogError("DbCommand->ToExecute() 出错 " + ex.Message); 451 throw new Exception(ex.Message); 452 } 453 } 454 #endregion 455 456 #region ** 仅执行,不返回输出参数 ** 457 /// <summary> 458 /// 根据存储过程执行 459 /// </summary> 460 public int Execute(string spName) 461 { 462 SqlCommand comd = CreateComd(spName); 463 return ToExecute(comd); 464 } 465 /// <summary> 466 /// 根据存储过程和参数执行 467 /// </summary> 468 public int Execute(string spName, DbParameters p) 469 { 470 SqlCommand comd = CreateComd(spName, p); 471 return ToExecute(comd); 472 } 473 /// <summary> 474 /// 执行sql语句 475 /// </summary> 476 public int ExecuteSql(string sql) 477 { 478 SqlCommand comd = CreateSqlComd(sql); 479 return ToExecute(comd); 480 } 481 482 /// <summary> 483 /// 执行带参数的SQL语句 484 /// </summary> 485 public int ExecuteSqlInt(string sql, DbParameters p) 486 { 487 SqlCommand comd = CreateSqlComd(sql, p); 488 return ToExecuteInt(comd); 489 } 490 public int ExecuteSql(string sql, DbParameters p) 491 { 492 SqlCommand comd = CreateSqlComd(sql, p); 493 return ToExecute(comd); 494 } 495 496 #endregion 497 498 #region ** 执行并返回输出参数 ** 499 /// <summary> 500 /// 执行并返回输出参数 501 /// </summary> 502 public string ExecuteOut(string spName, DbParameters p, string outParamName) 503 { 504 SqlCommand comd = CreateComd(spName, p); 505 //comd.Parameters.Add(new SqlParameter(outParamName, SqlDbType.VarChar, 50)); 506 //comd.Parameters[outParamName].Direction = ParameterDirection.Output; 507 508 try 509 { 510 ConnOpen(ref comd); 511 comd.ExecuteNonQuery(); 512 object o = comd.Parameters[outParamName].Value; 513 ConnClose(ref comd); 514 515 return (o == null) ? "" : o.ToString(); 516 } 517 catch (System.Exception ex) 518 { 519 ConnClose(ref comd); 520 Log.LogError("DbCommand->ExecuteOut() 出错 " + ex.Message); 521 throw new Exception(ex.Message); 522 } 523 } 524 525 /// <summary> 526 /// 执行并返回输出参数:默认输出参数 @Result Varchar(50) 527 /// </summary> 528 public string ExecuteOut(string spName, DbParameters p) 529 { 530 SqlCommand comd = CreateComd(spName, p); 531 comd.Parameters.Add(new SqlParameter("@Result", SqlDbType.VarChar, 50)); 532 comd.Parameters["@Result"].Direction = ParameterDirection.Output; 533 534 try 535 { 536 ConnOpen(ref comd); 537 comd.ExecuteNonQuery(); 538 object o = comd.Parameters["@Result"].Value; 539 ConnClose(ref comd); 540 541 return (o == null) ? "" : o.ToString(); 542 } 543 catch (System.Exception ex) 544 { 545 ConnClose(ref comd); 546 Log.LogError("DbCommand->ExecuteOut() 出错 " + ex.Message); 547 throw new Exception(ex.Message); 548 } 549 } 550 #endregion 551 552 #region ** 执行并返回输出参数 ** 553 /// <summary> 554 /// 执行存储过程,并返回输出参数 555 /// </summary> 556 public string ExecuteReturn(string spName, DbParameters p, string retParam) 557 { 558 SqlCommand comd = CreateComd(spName, p); 559 comd.Parameters.Add(new SqlParameter(retParam, SqlDbType.VarChar, 50)); 560 comd.Parameters[retParam].Direction = ParameterDirection.ReturnValue; 561 562 //comd.Parameters.Add(new SqlParameter("ReturnValue",SqlDbType.Int,4, ParameterDirection.ReturnValue, false, 0, 0,String.Empty, DataRowVersion.Default, null)); 563 564 try 565 { 566 ConnOpen(ref comd); 567 comd.ExecuteNonQuery(); 568 object o = comd.Parameters[retParam].Value; 569 ConnClose(ref comd); 570 571 return (o == null) ? "" : o.ToString(); 572 } 573 catch (System.Exception ex) 574 { 575 ConnClose(ref comd); 576 Log.LogError("DbCommand->ExecuteReturn() 出错 " + ex.Message); 577 throw new Exception(ex.Message); 578 } 579 } 580 public string ExecuteReturn(string spName, DbParameters p) 581 { 582 SqlCommand comd = CreateComd(spName, p); 583 comd.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.VarChar, 50)); 584 comd.Parameters["ReturnValue"].Direction = ParameterDirection.ReturnValue; 585 586 //comd.Parameters.Add(new SqlParameter("ReturnValue",SqlDbType.Int,4, ParameterDirection.ReturnValue, false, 0, 0,String.Empty, DataRowVersion.Default, null)); 587 588 try 589 { 590 ConnOpen(ref comd); 591 comd.ExecuteNonQuery(); 592 object o = comd.Parameters["ReturnValue"].Value; 593 ConnClose(ref comd); 594 595 return (o == null) ? "" : o.ToString(); 596 } 597 catch (System.Exception ex) 598 { 599 ConnClose(ref comd); 600 Log.LogError("DbCommand->ExecuteReturn() 出错 " + ex.Message); 601 throw new Exception(ex.Message); 602 } 603 } 604 /// <summary> 605 /// 执行Sql语句,并返回返回值 606 /// </summary> 607 public string ExecuteSqlReturn(string sql, DbParameters p, string retParam) 608 { 609 SqlCommand comd = CreateSqlComd(sql, p); 610 comd.Parameters.Add(new SqlParameter(retParam, SqlDbType.VarChar, 50)); 611 comd.Parameters[retParam].Direction = ParameterDirection.ReturnValue; 612 613 //comd.Parameters.Add(new SqlParameter("ReturnValue",SqlDbType.Int,4, ParameterDirection.ReturnValue, false, 0, 0,String.Empty, DataRowVersion.Default, null)); 614 615 try 616 { 617 ConnOpen(ref comd); 618 comd.ExecuteNonQuery(); 619 object o = comd.Parameters[retParam].Value; 620 ConnClose(ref comd); 621 622 return (o == null) ? "" : o.ToString(); 623 } 624 catch (System.Exception ex) 625 { 626 ConnClose(ref comd); 627 Log.LogError("DbCommand->ExecuteReturn() 出错 " + ex.Message); 628 throw new Exception(ex.Message); 629 } 630 } 631 /// <summary> 632 /// 根据Sql语句执行 633 /// </summary> 634 public string ExecuteSqlReturn(string sql, DbParameters p) 635 { 636 SqlCommand comd = CreateSqlComd(sql, p); 637 comd.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.VarChar, 50)); 638 comd.Parameters["ReturnValue"].Direction = ParameterDirection.ReturnValue; 639 640 //comd.Parameters.Add(new SqlParameter("ReturnValue",SqlDbType.Int,4, ParameterDirection.ReturnValue, false, 0, 0,String.Empty, DataRowVersion.Default, null)); 641 642 try 643 { 644 ConnOpen(ref comd); 645 comd.ExecuteNonQuery(); 646 object o = comd.Parameters["ReturnValue"].Value; 647 ConnClose(ref comd); 648 649 return (o == null) ? "" : o.ToString(); 650 } 651 catch (System.Exception ex) 652 { 653 ConnClose(ref comd); 654 Log.LogError("DbCommand->ExecuteReturn() 出错 " + ex.Message); 655 throw new Exception(ex.Message); 656 } 657 } 658 659 #endregion 660 661 } 662 }
    复制代码

    2.4调用实例

        读取DataTable:

        DataTable dt = new dbhelper().CreateSqlDataTable("select * from news ");

        读取单个字段:

        Object o=new dbhelper().CreateSqlScalar(“select title from news”);

        添加/修改删除

        String sql=””;

        DbParameters p = new DbParameters();

                  p.Add("@id", id);

        int iRes=new dbhelper().ExecuteSql(sql, p);

        调用实例在《Asp.Net Core 2.0 项目实战(11基于OnActionExecuting全局过滤器,页面操作权限过滤控制到按钮级》中也有用到,权限管理控制抽时间在完善一篇,等项目雏形出来了,开源出来配合代码再分享一下,Ado.Net封住调用实例到时一看便知。

    3.  EF Core数据库操作

      目前我了解到的EF Core已经支持大部分主流数据库如:Microsoft SQL Server、

      SQLite、Postgres (Npgsql)、 SQL Server Compact Edition、InMemory (for testing purposes);mysql现在不清楚是否已经支持了。

      我用的是数据库生成model这种方式,也就是DB First(数据库优先)。参考

      https://www.cnblogs.com/tianma3798/p/6835400.html,https://www.cnblogs.com/luwenlong/p/7804227.html

      注意Net Core下MVC没NetFreamWork 下MVC管理Model的图形界面,nf下数据里改个字段可以在vs上直接右键重新生成model,现在还不太清楚怎么处理,ef core操作方式与原来也略有不同,现在用ef core的时候感觉比较繁琐。另数据库新增,修改,删除字段后,ef core怎么能快捷操作,有知道的朋友请留言告知,大家共同学习。

    4.  总结

      无论技术怎么发展,还是由底层一代一代迭代出来的,基础还是要打好,Net Core2.0下操作数据库,牵扯到的内容太多,很多内容描述不出来,请大家配合代码理解实际动手操作一下,这里只能按心中所想配合项目实例列出重点,以及很多朋友可能会碰到的坑点,这里也当是自己的学习记录,有疑问欢迎留言大家讨论。

    IT黑马
  • 相关阅读:
    POJ3255(次短路)
    POJ2831(次小生成树问题)
    POJ1679(次小生成树)
    POJ2230(打印欧拉回路)
    HDU5469(树的dfs)
    JSON.parse()和JSON.stringify()的区别
    jQuery中.bind() .live() .delegate() .on()的区别
    javascript 伪数组和转化为标准数组
    JavaScript中本地对象、内置对象和宿主对象(转)
    获取非行间样式和定义样式(元素)
  • 原文地址:https://www.cnblogs.com/hmit/p/10768196.html
Copyright © 2011-2022 走看看