using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; //连接数据库所需命名空间 using System.Data; //连接数据库所需命名空间 namespace CMS.Admin //文件所在命名空间 { public partial class index : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string sql = "insert into [Column] (ColumnTitle, ColumnCode) values (@ColumnTitle, @ColumnCode)"; //带参数的sql语句 SqlParameter[] p = ]; //实例化参数数组 p[] = new SqlParameter("@ColumnTitle" , SqlDbType.NVarChar); //定义参数数组元素类型 p[] = new SqlParameter("@ColumnCode", SqlDbType.NVarChar); //定义参数数组元素类型 p[].Value = "入山栏目"; //给参数赋值 p[].Value = "; //给参数赋值 int i = OperationSql(sql , p); //调用操作数据库的方法 Response.Write(i); //向浏览器输出结果 } /// <summary> /// 获取配置的数据库连接字符转 /// </summary> public static string ConnStr { get { return System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString.ToString(); } } /// <summary> /// 操作数据库(增,删,改) /// </summary> /// <param name="sql">带参数或者不带参数的sql语句</param> /// <param name="parameter">sql语句中的参数数组</param> /// <returns>受影响的行数</returns> public static int OperationSql(string sql, SqlParameter[] parm) { SqlConnection conn = new SqlConnection(ConnStr); //实例化数据库 try { if (conn.State == ConnectionState.Closed) { conn.Open(); //判断数据库是否打开并打开 } SqlCommand cmd = new SqlCommand(sql, conn); //实例化连接命令 ) { foreach (SqlParameter p in parm) { cmd.Parameters.Add(p); } } return cmd.ExecuteNonQuery(); //返回受影响的行数 } catch { ; //执行失败返回 0 } finally { conn.Close(); //关闭数据库连接 } } } }