標籤:and fill reading sda comm 資料 ase use 資料庫
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Data.SqlClient; 7 using System.Data; 8 9 namespace MySchool.DAL 10 { 11 public class DBHelper 12 { 13 //private const string conn = "Data Source=.;Initial Catalog=MySchool;User ID=GaoFei;Password=111111"; 14 private const string conn = "Data Source=.;Initial Catalog=MySchool;User ID=sa;Password=sa"; 15 private static SqlConnection connection = new SqlConnection(conn); 16 17 18 /// <summary> 19 /// 讀取資料 20 /// </summary> 21 /// <returns></returns> 22 public static SqlDataReader Reader(string sql) 23 { 24 try 25 { 26 connection.Open(); 27 SqlCommand comm = new SqlCommand(sql, connection); 28 return comm.ExecuteReader(CommandBehavior.CloseConnection); 29 } 30 catch (Exception ex) 31 { 32 throw; 33 } 34 } 35 36 /// <summary> 37 /// 增刪改資料 38 /// </summary> 39 /// <param name="sql"></param> 40 /// <returns></returns> 41 public static int ExecuteNonQuery(string sql) 42 { 43 try 44 { 45 connection.Open(); //開啟資料庫連接 46 SqlCommand comm = new SqlCommand(sql, connection); 47 return comm.ExecuteNonQuery(); 48 } 49 catch (Exception ex) 50 { 51 throw; 52 } 53 finally 54 { 55 connection.Close(); 56 } 57 } 58 /// <summary> 59 /// 返回單個值 60 /// </summary> 61 /// <param name="sql"></param> 62 /// <returns></returns> 63 public static object ExecuteScalar(string sql) 64 { 65 try 66 { 67 connection.Open(); //開啟資料庫連接 68 SqlCommand comm = new SqlCommand(sql, connection); 69 return comm.ExecuteScalar(); 70 71 } 72 catch (Exception) 73 { 74 throw; 75 } 76 finally 77 { 78 connection.Close(); 79 } 80 } 81 /// <summary> 82 /// 返回資料集 83 /// </summary> 84 /// <param name="sql"></param> 85 /// <param name="tableName"></param> 86 /// <returns></returns> 87 public static DataSet Fill(string sql, string tableName) 88 { 89 try 90 { 91 connection.Open(); //開啟串連 92 //建立資料配接器對象 93 SqlDataAdapter sda = new SqlDataAdapter(sql, connection); 94 //建立資料集 95 DataSet ds = new DataSet(); 96 sda.Fill(ds, tableName); //填充資料集 97 return ds; 98 } 99 catch (Exception ex)100 {101 throw;102 //將異常引發出現103 // throw new Exception(e.Message);104 }105 finally106 {107 connection.Close();108 }109 }110 }111 }
C#_JDBC串連資料庫