C#_DBHelper_SQL數據庫操作類.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

1
public class DBHelper 2 { 3 static string connStr = "Workstation id = localhost;" + 4 "Integrated Security = SSPI;" + 5 "Database = 數據庫名字;";//填入SQL數據庫的登錄信息。 6 7 8 static SqlConnection conn = new SqlConnection(connStr); 9 10 public static SqlDataReader GetDataReader(string sql)//返回值是一個數組,可通過dr[0],dr[1]使用各字段的值 11 { 12 SqlConnection myConn = conn; 13 SqlDataReader dr = null; 14 15 try 16 { 17 if (myConn.State == ConnectionState.Closed) 18 { 19 myConn.Open(); 20 } 21 SqlCommand cmd = new SqlCommand(sql, myConn); 22 23 dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); 24 } 25 catch 26 { 27 28 if (myConn.State == ConnectionState.Open) 29 { 30 myConn.Close(); 31 } 32 33 } 34 return dr; 35 } 36 37 public static bool ExecuteNonQuery(string sql) //對於 UPDATE、INSERT 和 DELETE 語句,返回值為該命令所影響的行數。對於所有其他類型的語句,返回值為 -1。如果發生回滾,返回值也為 -1 38 { 39 int n = 0; 40 41 try 42 { 43 if (conn.State == ConnectionState.Closed) 44 { 45 conn.Open(); 46 } 47 SqlCommand cmd = new SqlCommand(sql, conn); 48 n = cmd.ExecuteNonQuery(); 49 50 } 51 catch 52 { 53 54 return false; 55 } 56 finally 57 { 58 if (conn.State == ConnectionState.Open) 59 { 60 conn.Close(); 61 } 62 } 63 return n > 0; 64 } 65 66 public static Object ExecuteScalar(string sql)//使用ExecuteScalar(),增刪改查如果成功,會返回一個對象,否則會返回一個null; 67 { 68 Object ob = null; 69 70 try 71 { 72 if (conn.State == ConnectionState.Closed) 73 { 74 conn.Open(); 75 } 76 SqlCommand cmd = new SqlCommand(sql, conn); 77 ob = cmd.ExecuteScalar(); 78 } 79 catch 80 { 81 return null; 82 } 83 finally 84 { 85 if (conn.State == ConnectionState.Open) 86 { 87 conn.Close(); 88 } 89 } 90 return ob; 91 } 92 } 93 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM