本文目錄
1. 摘要
2. Ado.Net數據庫操作封裝類
3. EF Core數據庫操作
4. 總結
Asp.Net Core2.0下操作MSSQL數據庫,這里介紹兩種操作方式,一種是.NET Framework的ADO.NET《Ado.Net百科》,另一種就是Net Core2.0下的一種orm操作EF Core,由於本人習慣Ado.Net編程模式,EF Core涉獵不是很深,推薦網友連接,本文有不寫的不到之處歡迎大家批評指正。
在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);
1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Data.SqlClient; 5 using System.Text; 6 7 namespace NC.Core 8 { 9 public class DbParameters 10 { 11 private List<SqlParameter> li; 12 13 //構造函數 14 public DbParameters() 15 { 16 li = new List<SqlParameter>(); 17 } 18 19 //單個參數的構造函數 20 public DbParameters(string strName, object strValue) 21 { 22 li = new List<SqlParameter>(); 23 this.Add(strName, strValue); 24 } 25 26 27 #region ** 屬性 ** 28 //長度 29 public int Length 30 { 31 get { return li.Count; } 32 } 33 //索引 34 public SqlParameter this[int k] 35 { 36 get 37 { 38 if (li.Contains(li[k])) 39 { 40 SqlParameter parm = li[k]; 41 return parm; 42 } 43 else 44 { 45 return null; 46 } 47 } 48 } 49 #endregion 50 51 #region ** 添加參數 52 //添加 Input 類型參數 53 public void Add(string sName, object sValue) 54 { 55 li.Add(new SqlParameter() 56 { 57 ParameterName = sName.Trim(), 58 Value = sValue ?? DBNull.Value, 59 Direction = ParameterDirection.Input, 60 }); 61 } 62 //添加 Output 類型參數 63 public void AddOut() 64 { 65 AddOut("@Result", "int", 4); 66 } 67 public void AddOut(string sName, string sDbType, int iSize) 68 { 69 li.Add(new SqlParameter() 70 { 71 ParameterName = sName, 72 SqlDbType = ConvertSqlDbType(sDbType), 73 Size = iSize, 74 Direction = ParameterDirection.Output, 75 }); 76 } 77 public void AddInputOutput(string sName) 78 { 79 li.Add(new SqlParameter() 80 { 81 ParameterName = sName, 82 Direction = ParameterDirection.InputOutput, 83 }); 84 } 85 public void AddInputOutput(string sName, string sDbType, int iSize) 86 { 87 li.Add(new SqlParameter() 88 { 89 ParameterName = sName, 90 SqlDbType = ConvertSqlDbType(sDbType), 91 Size = iSize, 92 Direction = ParameterDirection.InputOutput, 93 }); 94 } 95 //輸出測試內容 96 public void Output() 97 { 98 //netcore2.0里沒有HttpContext后續這里改為日志記錄 99 //System.Web.HttpContext.Current.Response.Write("參數輸出:---- <br />"); 100 101 for (int i = 0; i < li.Count; i++) 102 { 103 SqlParameter p = li[i]; 104 string pName = p.ParameterName; 105 string pVal = Convert.ToString(p.Value); 106 //System.Web.HttpContext.Current.Response.Write(pName + " 的值為: " + pVal + " <br />"); 107 } 108 } 109 #endregion 110 111 #region ** 參數轉換函數 112 //SqlDbType數據類型轉換 113 private SqlDbType ConvertSqlDbType(string strDbType) 114 { 115 SqlDbType t = new SqlDbType(); 116 switch (strDbType.Trim().ToLower()) 117 { 118 case "nvarchar": t = SqlDbType.NVarChar; break; 119 case "nchar": t = SqlDbType.NChar; break; 120 case "varchar": t = SqlDbType.VarChar; break; 121 case "char": t = SqlDbType.Char; break; 122 case "int": t = SqlDbType.Int; break; 123 case "datetime": t = SqlDbType.DateTime; break; 124 case "decimal": t = SqlDbType.Decimal; break; 125 case "bit": t = SqlDbType.Bit; break; 126 case "text": t = SqlDbType.Text; break; 127 case "ntext": t = SqlDbType.NText; break; 128 case "money": t = SqlDbType.Money; break; 129 case "float": t = SqlDbType.Float; break; 130 case "binary": t = SqlDbType.Binary; break; 131 } 132 return t; 133 } 134 135 #endregion 136 137 #region ** 清空參數集合 138 public void Clear() 139 { 140 li.Clear(); 141 } 142 #endregion 143 } 144 }
默認只有一個數據庫連接,多個數據庫連接的話再添加實例就可以了,注意這個類是從net freamwork下老項目直接修改得來,net core下並非所有的方法都有使用過。 增、刪、改、查均是SQL語句的命令,所以只要存在能向數據庫發送SQL腳本的接口則可以實現,Command,要發送腳本總要知道腳本往哪里發找到了Connection,執行完腳本數據庫向我們回發結果總要有一個承載 Reader、 Record。Asp.Net Core下提供的基礎方法如下,參考DbHelper類完善你自己的SqlHelper類吧。
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) 出錯\r\n" + 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) 出錯\r\n" + 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) 出錯\r\n" + 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) 出錯\r\n" + 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) 出錯\r\n" + 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) 出錯\r\n" + 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) 出錯\r\n" + 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) 出錯\r\n" + 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() 出錯\r\n" + 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() 出錯\r\n" + 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() 出錯\r\n" + 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() 出錯\r\n" + 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() 出錯\r\n" + 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() 出錯\r\n" + 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() 出錯\r\n" + 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() 出錯\r\n" + 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() 出錯\r\n" + 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() 出錯\r\n" + 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() 出錯\r\n" + ex.Message); 655 throw new Exception(ex.Message); 656 } 657 } 658 659 #endregion 660 661 } 662 }
讀取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封住調用實例到時一看便知。
目前我了解到的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怎么能快捷操作,有知道的朋友請留言告知,大家共同學習。
無論技術怎么發展,還是由底層一代一代迭代出來的,基礎還是要打好,Net Core2.0下操作數據庫,牽扯到的內容太多,很多內容描述不出來,請大家配合代碼理解實際動手操作一下,這里只能按心中所想配合項目實例列出重點,以及很多朋友可能會碰到的坑點,這里也當是自己的學習記錄,有疑問歡迎留言大家討論。
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。