判断是否存在某表的某个字段
select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
表是否存在
select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1类库中获取Config中配置字符串
1 public class PubConstant 2 { 3 /// <summary> 4 /// 获取固定连接字符串 5 /// </summary> 6 public static string ConnectionString 7 { 8 get 9 { 10 string _connectionString = ConfigurationManager.AppSettings["ConnectionString"]; 11 string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"]; 12 if (ConStringEncrypt == "true") 13 { 14 _connectionString = DESEncrypt.Decrypt(_connectionString); 15 } 16 return _connectionString; 17 } 18 } 19 20 /// <summary> 21 /// 动态得到web.config里配置项的数据库连接字符串。 22 /// </summary> 23 /// <param name="configName"></param> 24 /// <returns></returns> 25 public static string GetConnectionString(string configName) 26 { 27 string connectionString = ConfigurationManager.AppSettings[configName]; 28 string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"]; 29 if (ConStringEncrypt == "true") 30 { 31 connectionString = DESEncrypt.Decrypt(connectionString); 32 } 33 return connectionString; 34 }
类库中的DbHelperSql
1 namespace Maticsoft.DBUtility 2 { 3 /// <summary> 4 /// 数据访问基础类(基于SQLServer) 5 /// Copyright (C) 2004-2008 By LiTianPing 6 /// </summary> 7 public class DbHelperSQL 8 { 9 //数据库连接字符串(web.config来配置) 10 public static string connectionString = PubConstant.ConnectionString; 11 public DbHelperSQL() 12 { 13 } 14 15 #region 公用方法 16 /// <summary> 17 /// 判断是否存在某表的某个字段 18 /// </summary> 19 /// <param name="tableName">表名称</param> 20 /// <param name="columnName">列名称</param> 21 /// <returns>是否存在</returns> 22 public static bool ColumnExists(string tableName, string columnName) 23 { 24 string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'"; 25 object res = GetSingle(sql); 26 if (res == null) 27 { 28 return false; 29 } 30 return Convert.ToInt32(res) > 0; 31 } 32 public static int GetMaxID(string FieldName, string TableName) 33 { 34 string strsql = "select max(" + FieldName + ")+1 from " + TableName; 35 object obj = DbHelperSQL.GetSingle(strsql); 36 if (obj == null) 37 { 38 return 1; 39 } 40 else 41 { 42 return int.Parse(obj.ToString()); 43 } 44 } 45 public static bool Exists(string strSql) 46 { 47 object obj = GetSingle(strSql); 48 int cmdresult; 49 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) 50 { 51 cmdresult = 0; 52 } 53 else 54 { 55 cmdresult = int.Parse(obj.ToString()); 56 } 57 if (cmdresult == 0) 58 { 59 return false; 60 } 61 else 62 { 63 return true; 64 } 65 } 66 /// <summary> 67 /// 表是否存在 68 /// </summary> 69 /// <param name="TableName"></param> 70 /// <returns></returns> 71 public static bool TabExists(string TableName) 72 { 73 string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1"; 74 //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')"; 75 object obj = GetSingle(strsql); 76 int cmdresult; 77 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) 78 { 79 cmdresult = 0; 80 } 81 else 82 { 83 cmdresult = int.Parse(obj.ToString()); 84 } 85 if (cmdresult == 0) 86 { 87 return false; 88 } 89 else 90 { 91 return true; 92 } 93 } 94 public static bool Exists(string strSql, params SqlParameter[] cmdParms) 95 { 96 object obj = GetSingle(strSql, cmdParms); 97 int cmdresult; 98 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) 99 { 100 cmdresult = 0; 101 } 102 else 103 { 104 cmdresult = int.Parse(obj.ToString()); 105 } 106 if (cmdresult == 0) 107 { 108 return false; 109 } 110 else 111 { 112 return true; 113 } 114 } 115 #endregion 116 117 #region 执行简单SQL语句 118 119 /// <summary> 120 /// 执行SQL语句,返回影响的记录数 121 /// </summary> 122 /// <param name="SQLString">SQL语句</param> 123 /// <returns>影响的记录数</returns> 124 public static int ExecuteSql(string SQLString) 125 { 126 using (SqlConnection connection = new SqlConnection(connectionString)) 127 { 128 using (SqlCommand cmd = new SqlCommand(SQLString, connection)) 129 { 130 try 131 { 132 connection.Open(); 133 int rows = cmd.ExecuteNonQuery(); 134 return rows; 135 } 136 catch (System.Data.SqlClient.SqlException e) 137 { 138 connection.Close(); 139 throw e; 140 } 141 } 142 } 143 } 144 145 public static int ExecuteSqlByTime(string SQLString, int Times) 146 { 147 using (SqlConnection connection = new SqlConnection(connectionString)) 148 { 149 using (SqlCommand cmd = new SqlCommand(SQLString, connection)) 150 { 151 try 152 { 153 connection.Open(); 154 cmd.CommandTimeout = Times; 155 int rows = cmd.ExecuteNonQuery(); 156 return rows; 157 } 158 catch (System.Data.SqlClient.SqlException e) 159 { 160 connection.Close(); 161 throw e; 162 } 163 } 164 } 165 } 166 167 /// <summary> 168 /// 执行Sql和Oracle滴混合事务 169 /// </summary> 170 /// <param name="list">SQL命令行列表</param> 171 /// <param name="oracleCmdSqlList">Oracle命令行列表</param> 172 /// <returns>执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功</returns> 173 public static int ExecuteSqlTran(List<CommandInfo> list, List<CommandInfo> oracleCmdSqlList) 174 { 175 using (SqlConnection conn = new SqlConnection(connectionString)) 176 { 177 conn.Open(); 178 SqlCommand cmd = new SqlCommand(); 179 cmd.Connection = conn; 180 SqlTransaction tx = conn.BeginTransaction(); 181 cmd.Transaction = tx; 182 try 183 { 184 foreach (CommandInfo myDE in list) 185 { 186 string cmdText = myDE.CommandText; 187 SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; 188 PrepareCommand(cmd, conn, tx, cmdText, cmdParms); 189 if (myDE.EffentNextType == EffentNextType.SolicitationEvent) 190 { 191 if (myDE.CommandText.ToLower().IndexOf("count(") == -1) 192 { 193 tx.Rollback(); 194 throw new Exception("违背要求"+myDE.CommandText+"必须符合select count(..的格式"); 195 //return 0; 196 } 197 198 object obj = cmd.ExecuteScalar(); 199 bool isHave = false; 200 if (obj == null && obj == DBNull.Value) 201 { 202 isHave = false; 203 } 204 isHave = Convert.ToInt32(obj) > 0; 205 if (isHave) 206 { 207 //引发事件 208 myDE.OnSolicitationEvent(); 209 } 210 } 211 if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) 212 { 213 if (myDE.CommandText.ToLower().IndexOf("count(") == -1) 214 { 215 tx.Rollback(); 216 throw new Exception("SQL:违背要求" + myDE.CommandText + "必须符合select count(..的格式"); 217 //return 0; 218 } 219 220 object obj = cmd.ExecuteScalar(); 221 bool isHave = false; 222 if (obj == null && obj == DBNull.Value) 223 { 224 isHave = false; 225 } 226 isHave = Convert.ToInt32(obj) > 0; 227 228 if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) 229 { 230 tx.Rollback(); 231 throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须大于0"); 232 //return 0; 233 } 234 if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) 235 { 236 tx.Rollback(); 237 throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须等于0"); 238 //return 0; 239 } 240 continue; 241 } 242 int val = cmd.ExecuteNonQuery(); 243 if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) 244 { 245 tx.Rollback(); 246 throw new Exception("SQL:违背要求" + myDE.CommandText + "必须有影响行"); 247 //return 0; 248 } 249 cmd.Parameters.Clear(); 250 } 251 string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC"); 252 bool res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList); 253 if (!res) 254 { 255 tx.Rollback(); 256 throw new Exception("Oracle执行失败"); 257 // return -1; 258 } 259 tx.Commit(); 260 return 1; 261 } 262 catch (System.Data.SqlClient.SqlException e) 263 { 264 tx.Rollback(); 265 throw e; 266 } 267 catch (Exception e) 268 { 269 tx.Rollback(); 270 throw e; 271 } 272 } 273 } 274 /// <summary> 275 /// 执行多条SQL语句,实现数据库事务。 276 /// </summary> 277 /// <param name="SQLStringList">多条SQL语句</param> 278 public static int ExecuteSqlTran(List<String> SQLStringList) 279 { 280 using (SqlConnection conn = new SqlConnection(connectionString)) 281 { 282 conn.Open(); 283 SqlCommand cmd = new SqlCommand(); 284 cmd.Connection = conn; 285 SqlTransaction tx = conn.BeginTransaction(); 286 cmd.Transaction = tx; 287 try 288 { 289 int count = 0; 290 for (int n = 0; n < SQLStringList.Count; n++) 291 { 292 string strsql = SQLStringList[n]; 293 if (strsql.Trim().Length > 1) 294 { 295 cmd.CommandText = strsql; 296 count += cmd.ExecuteNonQuery(); 297 } 298 } 299 tx.Commit(); 300 return count; 301 } 302 catch 303 { 304 tx.Rollback(); 305 return 0; 306 } 307 } 308 } 309 /// <summary> 310 /// 执行带一个存储过程参数的的SQL语句。 311 /// </summary> 312 /// <param name="SQLString">SQL语句</param> 313 /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> 314 /// <returns>影响的记录数</returns> 315 public static int ExecuteSql(string SQLString, string content) 316 { 317 using (SqlConnection connection = new SqlConnection(connectionString)) 318 { 319 SqlCommand cmd = new SqlCommand(SQLString, connection); 320 System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); 321 myParameter.Value = content; 322 cmd.Parameters.Add(myParameter); 323 try 324 { 325 connection.Open(); 326 int rows = cmd.ExecuteNonQuery(); 327 return rows; 328 } 329 catch (System.Data.SqlClient.SqlException e) 330 { 331 throw e; 332 } 333 finally 334 { 335 cmd.Dispose(); 336 connection.Close(); 337 } 338 } 339 } 340 /// <summary> 341 /// 执行带一个存储过程参数的的SQL语句。 342 /// </summary> 343 /// <param name="SQLString">SQL语句</param> 344 /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> 345 /// <returns>影响的记录数</returns> 346 public static object ExecuteSqlGet(string SQLString, string content) 347 { 348 using (SqlConnection connection = new SqlConnection(connectionString)) 349 { 350 SqlCommand cmd = new SqlCommand(SQLString, connection); 351 System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); 352 myParameter.Value = content; 353 cmd.Parameters.Add(myParameter); 354 try 355 { 356 connection.Open(); 357 object obj = cmd.ExecuteScalar(); 358 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) 359 { 360 return null; 361 } 362 else 363 { 364 return obj; 365 } 366 } 367 catch (System.Data.SqlClient.SqlException e) 368 { 369 throw e; 370 } 371 finally 372 { 373 cmd.Dispose(); 374 connection.Close(); 375 } 376 } 377 } 378 /// <summary> 379 /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) 380 /// </summary> 381 /// <param name="strSQL">SQL语句</param> 382 /// <param name="fs">图像字节,数据库的字段类型为image的情况</param> 383 /// <returns>影响的记录数</returns> 384 public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) 385 { 386 using (SqlConnection connection = new SqlConnection(connectionString)) 387 { 388 SqlCommand cmd = new SqlCommand(strSQL, connection); 389 System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image); 390 myParameter.Value = fs; 391 cmd.Parameters.Add(myParameter); 392 try 393 { 394 connection.Open(); 395 int rows = cmd.ExecuteNonQuery(); 396 return rows; 397 } 398 catch (System.Data.SqlClient.SqlException e) 399 { 400 throw e; 401 } 402 finally 403 { 404 cmd.Dispose(); 405 connection.Close(); 406 } 407 } 408 } 409 410 /// <summary> 411 /// 执行一条计算查询结果语句,返回查询结果(object)。 412 /// </summary> 413 /// <param name="SQLString">计算查询结果语句</param> 414 /// <returns>查询结果(object)</returns> 415 public static object GetSingle(string SQLString) 416 { 417 using (SqlConnection connection = new SqlConnection(connectionString)) 418 { 419 using (SqlCommand cmd = new SqlCommand(SQLString, connection)) 420 { 421 try 422 { 423 connection.Open(); 424 object obj = cmd.ExecuteScalar(); 425 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) 426 { 427 return null; 428 } 429 else 430 { 431 return obj; 432 } 433 } 434 catch (System.Data.SqlClient.SqlException e) 435 { 436 connection.Close(); 437 throw e; 438 } 439 } 440 } 441 } 442 public static object GetSingle(string SQLString, int Times) 443 { 444 using (SqlConnection connection = new SqlConnection(connectionString)) 445 { 446 using (SqlCommand cmd = new SqlCommand(SQLString, connection)) 447 { 448 try 449 { 450 connection.Open(); 451 cmd.CommandTimeout = Times; 452 object obj = cmd.ExecuteScalar(); 453 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) 454 { 455 return null; 456 } 457 else 458 { 459 return obj; 460 } 461 } 462 catch (System.Data.SqlClient.SqlException e) 463 { 464 connection.Close(); 465 throw e; 466 } 467 } 468 } 469 } 470 /// <summary> 471 /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) 472 /// </summary> 473 /// <param name="strSQL">查询语句</param> 474 /// <returns>SqlDataReader</returns> 475 public static SqlDataReader ExecuteReader(string strSQL) 476 { 477 SqlConnection connection = new SqlConnection(connectionString); 478 SqlCommand cmd = new SqlCommand(strSQL, connection); 479 try 480 { 481 connection.Open(); 482 SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); 483 return myReader; 484 } 485 catch (System.Data.SqlClient.SqlException e) 486 { 487 throw e; 488 } 489 490 } 491 /// <summary> 492 /// 执行查询语句,返回DataSet 493 /// </summary> 494 /// <param name="SQLString">查询语句</param> 495 /// <returns>DataSet</returns> 496 public static DataSet Query(string SQLString) 497 { 498 using (SqlConnection connection = new SqlConnection(connectionString)) 499 { 500 DataSet ds = new DataSet(); 501 try 502 { 503 connection.Open(); 504 SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); 505 command.Fill(ds, "ds"); 506 } 507 catch (System.Data.SqlClient.SqlException ex) 508 { 509 throw new Exception(ex.Message); 510 } 511 return ds; 512 } 513 } 514 public static DataSet Query(string SQLString, int Times) 515 { 516 using (SqlConnection connection = new SqlConnection(connectionString)) 517 { 518 DataSet ds = new DataSet(); 519 try 520 { 521 connection.Open(); 522 SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); 523 command.SelectCommand.CommandTimeout = Times; 524 command.Fill(ds, "ds"); 525 } 526 catch (System.Data.SqlClient.SqlException ex) 527 { 528 throw new Exception(ex.Message); 529 } 530 return ds; 531 } 532 } 533 534 535 536 #endregion 537 538 #region 执行带参数的SQL语句 539 540 /// <summary> 541 /// 执行SQL语句,返回影响的记录数 542 /// </summary> 543 /// <param name="SQLString">SQL语句</param> 544 /// <returns>影响的记录数</returns> 545 public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms) 546 { 547 using (SqlConnection connection = new SqlConnection(connectionString)) 548 { 549 using (SqlCommand cmd = new SqlCommand()) 550 { 551 try 552 { 553 PrepareCommand(cmd, connection, null, SQLString, cmdParms); 554 int rows = cmd.ExecuteNonQuery(); 555 cmd.Parameters.Clear(); 556 return rows; 557 } 558 catch (System.Data.SqlClient.SqlException e) 559 { 560 throw e; 561 } 562 } 563 } 564 } 565 566 567 /// <summary> 568 /// 执行多条SQL语句,实现数据库事务。 569 /// </summary> 570 /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> 571 public static void ExecuteSqlTran(Hashtable SQLStringList) 572 { 573 using (SqlConnection conn = new SqlConnection(connectionString)) 574 { 575 conn.Open(); 576 using (SqlTransaction trans = conn.BeginTransaction()) 577 { 578 SqlCommand cmd = new SqlCommand(); 579 try 580 { 581 //循环 582 foreach (DictionaryEntry myDE in SQLStringList) 583 { 584 string cmdText = myDE.Key.ToString(); 585 SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; 586 PrepareCommand(cmd, conn, trans, cmdText, cmdParms); 587 int val = cmd.ExecuteNonQuery(); 588 cmd.Parameters.Clear(); 589 } 590 trans.Commit(); 591 } 592 catch 593 { 594 trans.Rollback(); 595 throw; 596 } 597 } 598 } 599 } 600 /// <summary> 601 /// 执行多条SQL语句,实现数据库事务。 602 /// </summary> 603 /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> 604 public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList) 605 { 606 using (SqlConnection conn = new SqlConnection(connectionString)) 607 { 608 conn.Open(); 609 using (SqlTransaction trans = conn.BeginTransaction()) 610 { 611 SqlCommand cmd = new SqlCommand(); 612 try 613 { int count = 0; 614 //循环 615 foreach (CommandInfo myDE in cmdList) 616 { 617 string cmdText = myDE.CommandText; 618 SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; 619 PrepareCommand(cmd, conn, trans, cmdText, cmdParms); 620 621 if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) 622 { 623 if (myDE.CommandText.ToLower().IndexOf("count(") == -1) 624 { 625 trans.Rollback(); 626 return 0; 627 } 628 629 object obj = cmd.ExecuteScalar(); 630 bool isHave = false; 631 if (obj == null && obj == DBNull.Value) 632 { 633 isHave = false; 634 } 635 isHave = Convert.ToInt32(obj) > 0; 636 637 if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) 638 { 639 trans.Rollback(); 640 return 0; 641 } 642 if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) 643 { 644 trans.Rollback(); 645 return 0; 646 } 647 continue; 648 } 649 int val = cmd.ExecuteNonQuery(); 650 count += val; 651 if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) 652 { 653 trans.Rollback(); 654 return 0; 655 } 656 cmd.Parameters.Clear(); 657 } 658 trans.Commit(); 659 return count; 660 } 661 catch 662 { 663 trans.Rollback(); 664 throw; 665 } 666 } 667 } 668 } 669 /// <summary> 670 /// 执行多条SQL语句,实现数据库事务。 671 /// </summary> 672 /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> 673 public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList) 674 { 675 using (SqlConnection conn = new SqlConnection(connectionString)) 676 { 677 conn.Open(); 678 using (SqlTransaction trans = conn.BeginTransaction()) 679 { 680 SqlCommand cmd = new SqlCommand(); 681 try 682 { 683 int indentity = 0; 684 //循环 685 foreach (CommandInfo myDE in SQLStringList) 686 { 687 string cmdText = myDE.CommandText; 688 SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; 689 foreach (SqlParameter q in cmdParms) 690 { 691 if (q.Direction == ParameterDirection.InputOutput) 692 { 693 q.Value = indentity; 694 } 695 } 696 PrepareCommand(cmd, conn, trans, cmdText, cmdParms); 697 int val = cmd.ExecuteNonQuery(); 698 foreach (SqlParameter q in cmdParms) 699 { 700 if (q.Direction == ParameterDirection.Output) 701 { 702 indentity = Convert.ToInt32(q.Value); 703 } 704 } 705 cmd.Parameters.Clear(); 706 } 707 trans.Commit(); 708 } 709 catch 710 { 711 trans.Rollback(); 712 throw; 713 } 714 } 715 } 716 } 717 /// <summary> 718 /// 执行多条SQL语句,实现数据库事务。 719 /// </summary> 720 /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> 721 public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList) 722 { 723 using (SqlConnection conn = new SqlConnection(connectionString)) 724 { 725 conn.Open(); 726 using (SqlTransaction trans = conn.BeginTransaction()) 727 { 728 SqlCommand cmd = new SqlCommand(); 729 try 730 { 731 int indentity = 0; 732 //循环 733 foreach (DictionaryEntry myDE in SQLStringList) 734 { 735 string cmdText = myDE.Key.ToString(); 736 SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; 737 foreach (SqlParameter q in cmdParms) 738 { 739 if (q.Direction == ParameterDirection.InputOutput) 740 { 741 q.Value = indentity; 742 } 743 } 744 PrepareCommand(cmd, conn, trans, cmdText, cmdParms); 745 int val = cmd.ExecuteNonQuery(); 746 foreach (SqlParameter q in cmdParms) 747 { 748 if (q.Direction == ParameterDirection.Output) 749 { 750 indentity = Convert.ToInt32(q.Value); 751 } 752 } 753 cmd.Parameters.Clear(); 754 } 755 trans.Commit(); 756 } 757 catch 758 { 759 trans.Rollback(); 760 throw; 761 } 762 } 763 } 764 } 765 /// <summary> 766 /// 执行一条计算查询结果语句,返回查询结果(object)。 767 /// </summary> 768 /// <param name="SQLString">计算查询结果语句</param> 769 /// <returns>查询结果(object)</returns> 770 public static object GetSingle(string SQLString, params SqlParameter[] cmdParms) 771 { 772 using (SqlConnection connection = new SqlConnection(connectionString)) 773 { 774 using (SqlCommand cmd = new SqlCommand()) 775 { 776 try 777 { 778 PrepareCommand(cmd, connection, null, SQLString, cmdParms); 779 object obj = cmd.ExecuteScalar(); 780 cmd.Parameters.Clear(); 781 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) 782 { 783 return null; 784 } 785 else 786 { 787 return obj; 788 } 789 } 790 catch (System.Data.SqlClient.SqlException e) 791 { 792 throw e; 793 } 794 } 795 } 796 } 797 798 /// <summary> 799 /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) 800 /// </summary> 801 /// <param name="strSQL">查询语句</param> 802 /// <returns>SqlDataReader</returns> 803 public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms) 804 { 805 SqlConnection connection = new SqlConnection(connectionString); 806 SqlCommand cmd = new SqlCommand(); 807 try 808 { 809 PrepareCommand(cmd, connection, null, SQLString, cmdParms); 810 SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); 811 cmd.Parameters.Clear(); 812 return myReader; 813 } 814 catch (System.Data.SqlClient.SqlException e) 815 { 816 throw e; 817 } 818 // finally 819 // { 820 // cmd.Dispose(); 821 // connection.Close(); 822 // } 823 824 } 825 826 /// <summary> 827 /// 执行查询语句,返回DataSet 828 /// </summary> 829 /// <param name="SQLString">查询语句</param> 830 /// <returns>DataSet</returns> 831 public static DataSet Query(string SQLString, params SqlParameter[] cmdParms) 832 { 833 using (SqlConnection connection = new SqlConnection(connectionString)) 834 { 835 SqlCommand cmd = new SqlCommand(); 836 PrepareCommand(cmd, connection, null, SQLString, cmdParms); 837 using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 838 { 839 DataSet ds = new DataSet(); 840 try 841 { 842 da.Fill(ds, "ds"); 843 cmd.Parameters.Clear(); 844 } 845 catch (System.Data.SqlClient.SqlException ex) 846 { 847 throw new Exception(ex.Message); 848 } 849 return ds; 850 } 851 } 852 } 853 854 855 private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms) 856 { 857 if (conn.State != ConnectionState.Open) 858 conn.Open(); 859 cmd.Connection = conn; 860 cmd.CommandText = cmdText; 861 if (trans != null) 862 cmd.Transaction = trans; 863 cmd.CommandType = CommandType.Text;//cmdType; 864 if (cmdParms != null) 865 { 866 foreach (SqlParameter parameter in cmdParms) 867 { 868 if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && 869 (parameter.Value == null)) 870 { 871 parameter.Value = DBNull.Value; 872 } 873 cmd.Parameters.Add(parameter); 874 } 875 } 876 } 877 878 #endregion 879 880 #region 存储过程操作 881 882 /// <summary> 883 /// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) 884 /// </summary> 885 /// <param name="storedProcName">存储过程名</param> 886 /// <param name="parameters">存储过程参数</param> 887 /// <returns>SqlDataReader</returns> 888 public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters) 889 { 890 SqlConnection connection = new SqlConnection(connectionString); 891 SqlDataReader returnReader; 892 connection.Open(); 893 SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); 894 command.CommandType = CommandType.StoredProcedure; 895 returnReader = command.ExecuteReader(CommandBehavior.CloseConnection); 896 return returnReader; 897 898 } 899 900 901 /// <summary> 902 /// 执行存储过程 903 /// </summary> 904 /// <param name="storedProcName">存储过程名</param> 905 /// <param name="parameters">存储过程参数</param> 906 /// <param name="tableName">DataSet结果中的表名</param> 907 /// <returns>DataSet</returns> 908 public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName) 909 { 910 using (SqlConnection connection = new SqlConnection(connectionString)) 911 { 912 DataSet dataSet = new DataSet(); 913 connection.Open(); 914 SqlDataAdapter sqlDA = new SqlDataAdapter(); 915 sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); 916 sqlDA.Fill(dataSet, tableName); 917 connection.Close(); 918 return dataSet; 919 } 920 } 921 public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times) 922 { 923 using (SqlConnection connection = new SqlConnection(connectionString)) 924 { 925 DataSet dataSet = new DataSet(); 926 connection.Open(); 927 SqlDataAdapter sqlDA = new SqlDataAdapter(); 928 sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); 929 sqlDA.SelectCommand.CommandTimeout = Times; 930 sqlDA.Fill(dataSet, tableName); 931 connection.Close(); 932 return dataSet; 933 } 934 } 935 936 937 /// <summary> 938 /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值) 939 /// </summary> 940 /// <param name="connection">数据库连接</param> 941 /// <param name="storedProcName">存储过程名</param> 942 /// <param name="parameters">存储过程参数</param> 943 /// <returns>SqlCommand</returns> 944 private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) 945 { 946 SqlCommand command = new SqlCommand(storedProcName, connection); 947 command.CommandType = CommandType.StoredProcedure; 948 foreach (SqlParameter parameter in parameters) 949 { 950 if (parameter != null) 951 { 952 // 检查未分配值的输出参数,将其分配以DBNull.Value. 953 if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && 954 (parameter.Value == null)) 955 { 956 parameter.Value = DBNull.Value; 957 } 958 command.Parameters.Add(parameter); 959 } 960 } 961 962 return command; 963 } 964 965 /// <summary> 966 /// 执行存储过程,返回影响的行数 967 /// </summary> 968 /// <param name="storedProcName">存储过程名</param> 969 /// <param name="parameters">存储过程参数</param> 970 /// <param name="rowsAffected">影响的行数</param> 971 /// <returns></returns> 972 public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) 973 { 974 using (SqlConnection connection = new SqlConnection(connectionString)) 975 { 976 int result; 977 connection.Open(); 978 SqlCommand command = BuildIntCommand(connection, storedProcName, parameters); 979 rowsAffected = command.ExecuteNonQuery(); 980 result = (int)command.Parameters["ReturnValue"].Value; 981 //Connection.Close(); 982 return result; 983 } 984 } 985 986 /// <summary> 987 /// 创建 SqlCommand 对象实例(用来返回一个整数值) 988 /// </summary> 989 /// <param name="storedProcName">存储过程名</param> 990 /// <param name="parameters">存储过程参数</param> 991 /// <returns>SqlCommand 对象实例</returns> 992 private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) 993 { 994 SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); 995 command.Parameters.Add(new SqlParameter("ReturnValue", 996 SqlDbType.Int, 4, ParameterDirection.ReturnValue, 997 false, 0, 0, string.Empty, DataRowVersion.Default, null)); 998 return command; 999 } 1000 #endregion 1001 1002 #region 添加一个传连接字符串的简单执行sql语句 2009-2-4 1003 /// <summary> 1004 /// 执行SQL语句,返回影响的记录数 1005 /// </summary> 1006 /// <param name="SQLString">SQL语句</param> 1007 /// <param name="strConnectionString">连接字符串</param> 1008 /// <returns>影响的记录数</returns> 1009 public static int ExecuteSql(string SQLString ,string strConnectionString,params SqlParameter[] cmdParms) 1010 { 1011 using (SqlConnection connection = new SqlConnection(strConnectionString)) 1012 { 1013 using (SqlCommand cmd = new SqlCommand()) 1014 { 1015 try 1016 { 1017 PrepareCommand(cmd, connection, null, SQLString, cmdParms); 1018 int rows = cmd.ExecuteNonQuery(); 1019 cmd.Parameters.Clear(); 1020 return rows; 1021 } 1022 catch (System.Data.SqlClient.SqlException e) 1023 { 1024 throw e; 1025 } 1026 } 1027 } 1028 } 1029 1030 /// <summary> 1031 /// 执行查询语句,返回DataSet 1032 /// </summary> 1033 /// <param name="SQLString">查询语句</param> 1034 /// <param name="strConnectionString">连接字符串</param> 1035 /// <returns>DataSet</returns> 1036 public static DataSet Query(string SQLString,string strConnectionString) 1037 { 1038 using (SqlConnection connection = new SqlConnection(strConnectionString)) 1039 { 1040 DataSet ds = new DataSet(); 1041 try 1042 { 1043 connection.Open(); 1044 SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); 1045 command.Fill(ds, "ds"); 1046 } 1047 catch (System.Data.SqlClient.SqlException ex) 1048 { 1049 throw new Exception(ex.Message); 1050 } 1051 return ds; 1052 } 1053 } 1054 #endregion 1055 } 1056 1057 }
类库中的SQLHelper
1 using System; 2 using System.Configuration; 3 using System.Data; 4 using System.Data.SqlClient; 5 using System.Collections; 6 7 namespace Maticsoft.DBUtility 8 { 9 10 /// <summary> 11 /// The SqlHelper class is intended to encapsulate high performance, 12 /// scalable best practices for common uses of SqlClient. 13 /// </summary> 14 public abstract class SqlHelper 15 { 16 17 //Database connection strings 18 public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.AppSettings["SQLConnString1"]; 19 public static readonly string ConnectionStringInventoryDistributedTransaction = ConfigurationManager.AppSettings["SQLConnString2"]; 20 public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.AppSettings["SQLConnString3"]; 21 public static readonly string ConnectionStringProfile = ConfigurationManager.AppSettings["SQLProfileConnString"]; 22 23 // Hashtable to store cached parameters 24 private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); 25 26 /// <summary> 27 /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 28 /// using the provided parameters. 29 /// </summary> 30 /// <remarks> 31 /// e.g.: 32 /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); 33 /// </remarks> 34 /// <param name="connectionString">a valid connection string for a SqlConnection</param> 35 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> 36 /// <param name="commandText">the stored procedure name or T-SQL command</param> 37 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> 38 /// <returns>an int representing the number of rows affected by the command</returns> 39 public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) 40 { 41 42 SqlCommand cmd = new SqlCommand(); 43 44 using (SqlConnection conn = new SqlConnection(connectionString)) 45 { 46 PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); 47 int val = cmd.ExecuteNonQuery(); 48 cmd.Parameters.Clear(); 49 return val; 50 } 51 } 52 53 /// <summary> 54 /// Execute a SqlCommand (that returns no resultset) against an existing database connection 55 /// using the provided parameters. 56 /// </summary> 57 /// <remarks> 58 /// e.g.: 59 /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); 60 /// </remarks> 61 /// <param name="conn">an existing database connection</param> 62 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> 63 /// <param name="commandText">the stored procedure name or T-SQL command</param> 64 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> 65 /// <returns>an int representing the number of rows affected by the command</returns> 66 public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) 67 { 68 69 SqlCommand cmd = new SqlCommand(); 70 71 PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); 72 int val = cmd.ExecuteNonQuery(); 73 cmd.Parameters.Clear(); 74 return val; 75 } 76 77 /// <summary> 78 /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction 79 /// using the provided parameters. 80 /// </summary> 81 /// <remarks> 82 /// e.g.: 83 /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); 84 /// </remarks> 85 /// <param name="trans">an existing sql transaction</param> 86 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> 87 /// <param name="commandText">the stored procedure name or T-SQL command</param> 88 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> 89 /// <returns>an int representing the number of rows affected by the command</returns> 90 public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) 91 { 92 SqlCommand cmd = new SqlCommand(); 93 PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters); 94 int val = cmd.ExecuteNonQuery(); 95 cmd.Parameters.Clear(); 96 return val; 97 } 98 99 /// <summary> 100 /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 101 /// using the provided parameters. 102 /// </summary> 103 /// <remarks> 104 /// e.g.: 105 /// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); 106 /// </remarks> 107 /// <param name="connectionString">a valid connection string for a SqlConnection</param> 108 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> 109 /// <param name="commandText">the stored procedure name or T-SQL command</param> 110 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> 111 /// <returns>A SqlDataReader containing the results</returns> 112 public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) 113 { 114 SqlCommand cmd = new SqlCommand(); 115 SqlConnection conn = new SqlConnection(connectionString); 116 117 // we use a try/catch here because if the method throws an exception we want to 118 // close the connection throw code, because no datareader will exist, hence the 119 // commandBehaviour.CloseConnection will not work 120 try 121 { 122 PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); 123 SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); 124 cmd.Parameters.Clear(); 125 return rdr; 126 } 127 catch 128 { 129 conn.Close(); 130 throw; 131 } 132 } 133 134 /// <summary> 135 /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string 136 /// using the provided parameters. 137 /// </summary> 138 /// <remarks> 139 /// e.g.: 140 /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); 141 /// </remarks> 142 /// <param name="connectionString">a valid connection string for a SqlConnection</param> 143 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> 144 /// <param name="commandText">the stored procedure name or T-SQL command</param> 145 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> 146 /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> 147 public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) 148 { 149 SqlCommand cmd = new SqlCommand(); 150 151 using (SqlConnection connection = new SqlConnection(connectionString)) 152 { 153 PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); 154 object val = cmd.ExecuteScalar(); 155 cmd.Parameters.Clear(); 156 return val; 157 } 158 } 159 160 /// <summary> 161 /// Execute a SqlCommand that returns the first column of the first record against an existing database connection 162 /// using the provided parameters. 163 /// </summary> 164 /// <remarks> 165 /// e.g.: 166 /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); 167 /// </remarks> 168 /// <param name="conn">an existing database connection</param> 169 /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> 170 /// <param name="commandText">the stored procedure name or T-SQL command</param> 171 /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> 172 /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> 173 public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) 174 { 175 176 SqlCommand cmd = new SqlCommand(); 177 178 PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); 179 object val = cmd.ExecuteScalar(); 180 cmd.Parameters.Clear(); 181 return val; 182 } 183 184 /// <summary> 185 /// add parameter array to the cache 186 /// </summary> 187 /// <param name="cacheKey">Key to the parameter cache</param> 188 /// <param name="cmdParms">an array of SqlParamters to be cached</param> 189 public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters) 190 { 191 parmCache[cacheKey] = commandParameters; 192 } 193 194 /// <summary> 195 /// Retrieve cached parameters 196 /// </summary> 197 /// <param name="cacheKey">key used to lookup parameters</param> 198 /// <returns>Cached SqlParamters array</returns> 199 public static SqlParameter[] GetCachedParameters(string cacheKey) 200 { 201 SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey]; 202 203 if (cachedParms == null) 204 return null; 205 206 SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length]; 207 208 for (int i = 0, j = cachedParms.Length; i < j; i++) 209 clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone(); 210 211 return clonedParms; 212 } 213 214 /// <summary> 215 /// Prepare a command for execution 216 /// </summary> 217 /// <param name="cmd">SqlCommand object</param> 218 /// <param name="conn">SqlConnection object</param> 219 /// <param name="trans">SqlTransaction object</param> 220 /// <param name="cmdType">Cmd type e.g. stored procedure or text</param> 221 /// <param name="cmdText">Command text, e.g. Select * from Products</param> 222 /// <param name="cmdParms">SqlParameters to use in the command</param> 223 private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) 224 { 225 if (conn.State != ConnectionState.Open) 226 conn.Open(); 227 228 cmd.Connection = conn; 229 cmd.CommandText = cmdText; 230 231 if (trans != null) 232 cmd.Transaction = trans; 233 234 cmd.CommandType = cmdType; 235 236 if (cmdParms != null) 237 { 238 foreach (SqlParameter parm in cmdParms) 239 cmd.Parameters.Add(parm); 240 } 241 } 242 } 243 }
向数据库中存储图片
1 /// <summary> 2 /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) 3 /// </summary> 4 /// <param name="strSQL">SQL语句</param> 5 /// <param name="fs">图像字节,数据库的字段类型为image的情况</param> 6 /// <returns>影响的记录数</returns> 7 public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) 8 { 9 using (SqlConnection connection = new SqlConnection(connectionString)) 10 { 11 SqlCommand cmd = new SqlCommand(strSQL, connection); 12 System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image); 13 myParameter.Value = fs; 14 cmd.Parameters.Add(myParameter); 15 try 16 { 17 connection.Open(); 18 int rows = cmd.ExecuteNonQuery(); 19 return rows; 20 } 21 catch (System.Data.SqlClient.SqlException e) 22 { 23 throw e; 24 } 25 finally 26 { 27 cmd.Dispose(); 28 connection.Close(); 29 } 30 } 31 }
返回ds
1 /// <summary> 2 /// 执行查询语句,返回DataSet 3 /// </summary> 4 /// <param name="SQLString">查询语句</param> 5 /// <returns>DataSet</returns> 6 public static DataSet Query(string SQLString) 7 { 8 using (SqlConnection connection = new SqlConnection(connectionString)) 9 { 10 DataSet ds = new DataSet(); 11 try 12 { 13 connection.Open(); 14 SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); 15 command.Fill(ds, "ds"); 16 } 17 catch (System.Data.SqlClient.SqlException ex) 18 { 19 throw new Exception(ex.Message); 20 } 21 return ds; 22 } 23 }