发布网友 发布时间:2022-05-02 12:52
共1个回答
懂视网 时间:2022-05-02 13:20
1 <connectionStrings> 2 <add name="connStr" connectionString="server=.;uid=sa;pwd=****;database=****;Charset=utf8"/> 3 </connectionStrings>
1 using System; 2 using System.Collections.Generic; 3 using System.Configuration; 4 using System.Data; 5 using System.Data.SqlClient; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 10 namespace ConsoleApplication1 11 { 12 class SqlHelper 13 { 14 //ADO.net中的SqlHelper 15 16 public static readonly string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; 17 18 public static SqlConnection CreateConnection() 19 { 20 SqlConnection conn = new SqlConnection(connStr); 21 conn.Open(); 22 return conn; 23 } 24 25 public static int ExecuteNonQuery(SqlConnection conn, string sql, params SqlParameter[] parameters) 26 { 27 using (SqlCommand cmd = conn.CreateCommand()) 28 { 29 cmd.CommandText = sql; 30 cmd.Parameters.AddRange(parameters); 31 return cmd.ExecuteNonQuery(); 32 } 33 } 34 35 public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters) 36 { 37 using (SqlConnection conn = CreateConnection()) 38 { 39 return ExecuteNonQuery(conn, sql, parameters); 40 } 41 } 42 43 public static object ExecuteScalar(SqlConnection conn, string sql, params SqlParameter[] parameters) 44 { 45 using (SqlCommand cmd = conn.CreateCommand()) 46 { 47 cmd.CommandText = sql; 48 cmd.Parameters.AddRange(parameters); 49 return cmd.ExecuteScalar(); 50 } 51 } 52 53 public static object ExecuteScalar(string sql, params SqlParameter[] parameters) 54 { 55 using (SqlConnection conn = CreateConnection()) 56 { 57 return ExecuteScalar(conn, sql, parameters); 58 } 59 } 60 61 public static DataTable ExecuteQuery(SqlConnection conn, string sql, params SqlParameter[] parameters) 62 { 63 DataTable table = new DataTable(); 64 using (SqlCommand cmd = conn.CreateCommand()) 65 { 66 cmd.CommandText = sql; 67 cmd.Parameters.AddRange(parameters); 68 using (SqlDataReader reader = cmd.ExecuteReader()) 69 { 70 table.Load(reader); 71 return table; 72 } 73 } 74 75 } 76 77 public static DataTable ExecuteQuery(string sql, params SqlParameter[] parameters) 78 { 79 using (SqlConnection conn = CreateConnection()) 80 { 81 return ExecuteQuery(conn, sql, parameters); 82 } 83 } 84 } 85 }SqlHelper
复习SqlHelper
标签:ble turn log 技术分享 closed reader serve utf8 public