using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace 数据库 { class CommandSqlHelper { /// <summary> /// 数据库连接字符串 /// </summary> private string ConnectionString { get { return ConfigurationManager.ConnectionStrings["connLocalhost"].ToString(); } } /// <summary> /// 增,删,改数据库(sql语句, sql语句的参数) /// </summary> /// <returns></returns> private int DbOperation(string sql, SqlParameter[] parm) { //创建连接对象 SqlConnection conn = new SqlConnection(ConnectionString); try { //创建命令对象 SqlCommand command = new SqlCommand(sql, conn); //判断连接对象是否打开(未打开时打开) //ConnectionState 枚举类型 => closed连接状态关闭 Broken连接状态中断 if (conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken) { conn.Open(); } //给命令对象添加参数 if (parm != null && parm.Length != 0) { foreach (SqlParameter par in parm) { command.Parameters.Add(par); } } //执行并返回受影响的行数 return command.ExecuteNonQuery(); } catch (Exception ex) { //抛出异常(ex.Message => 异常信息) throw new Exception(ex.Message); } finally { //关闭数据库 conn.Close(); } } /// <summary> /// 对外暴漏的测试方法 /// </summary> public static void Show() { CommandSqlHelper command = new CommandSqlHelper(); int result = command.DbOperation("update [User] [UserAge] = 100 where [UserAge] = 26", null); if (result > 0) { Console.WriteLine("操作成功{0}行改变", result); } else { Console.WriteLine("操作失败"); } } } }
时间: 2024-10-14 12:32:36