using Sqystem.Data;using System.Data.SqlClient;using System.Configuration;//引用一个库Ststem.configuration//修改根目录的web.config文件configuration//最外层节点......connectionStringsadd n...
using Sqystem.Data; using System.Data.SqlClient; using System.Configuration; //引用一个库Ststem.configuration //修改根目录的web.config文件 <configuration>//最外层节点 ...... <connectionStrings> <add name="connString" connectionString = "Sqerver=.;DataBase=StudentManage;Uid=sa;Pwd=scale2018@"> </connectionStrings> ...... </configuration> //数据库通用访问类 class SQLHelper { //数据库连接字符串 private static string connString = ConfigurationManager.ConnectionStrings["connString"].ToString(); //写入日志文件 public void WriteLog(string msg) { FileStream fs = FileStream("1.log",fileMode.Append); StreamWriter sw = new StreamWriter(fs); sw.writeLine(DateTime.Now.ToString()+" "+ msg); sw.Close(); fs.Close(); } //数据库更新 public static int Update(string sql) { SqlConnection conn = new SqlConnection(connString); SqlConnection cmd = new SqlCommand(sql,conn); try { conn.Open(); return cmd.ExecuteNoQuery(); } catch(Exception ex) { WriteLog("执行更新时发生异常"+ex.Message); throw ex; } finally { conn.Close(); } } public static object GetSingleResult(string sql) { Sqlconnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(sql,conn); try { conn.Open(); return cmd.ExecuteScalar(); } catch(Exception ex) { WriteLog("执行单一结果查询"+ex.message); throw ex; } finally { conn.Close(); } } //返回结果集 public static SqlDataReader GetReader(string sql) { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(sql,conn); try { conn.Open(); retrun cmd.ExecuteReader(CommandBehavior.CloseConnection);//不能在此关闭连接 } catch(Exception ex) { WriteLog("读取结果集发生异常"+ex.message); throw ex; } } //带参数的存储过程 public static int Update(string sqlOrProcedureName,SqlParameter[]param,bool isProcedure) { SqlConnection conn = new SqlConnection(connString); SqlConnection cmd = new SqlCommand(sqlOrProcedureName,conn); if(isProcedure) { cmd.CommandType = CommmandType.StoredProcedure; } try { conn.Open(); cmd.Parameters.AddRang(param); return cmd.ExecuteNoQuery(); } catch(Exception ex) { WriteLog("执行更新时发生异常"+ex.Message); throw ex; } finally { conn.Close(); } } }
沃梦达教程
本文标题为:C#数据库操作
基础教程推荐
猜你喜欢
- C# 读写XML文件实例代码 2023-02-08
- c# – Oracle实体框架 – 调用自定义函数(EDIT_DISTANCE) 2023-11-22
- c# this关键字用法代码详解 2023-02-08
- C# 数组删除元素的实现示例 2023-04-27
- C# 使用WPF 用MediaElement控件实现视频循环播放 2022-12-11
- C#中Lambda表达式的用法 2023-05-30
- C# Datatable的几种用法小结 2023-03-29
- WPF基础教程之元素绑定详解 2023-01-11
- c#在WebAPI使用Session的方法 2022-12-26
- C#开发Winform实现窗体间相互传值 2023-05-26