连接数据库 /**//// <summary> /// connecting to Database /// ["personal"]--根据Web.config可更改 /// </summary> public string strConn = ConfigurationManager.ConnectionStrings["SoftBlogConnectionString1"].ConnectionString; 以前用这个方法执行一句SQL语句 /**//// <summary> /// executing SQL commands-执行一段SQL语句 /// </summary> /// <param name="strSQL">string</param> /// <returns>return int</returns> public void dbExecuteSql(string strSQL) { SqlConnection myCn = new SqlConnection(strConn); SqlCommand myCmd = new SqlCommand(strSQL, myCn); try { myCn.Open(); myCmd.ExecuteNonQuery(); } catch (System.Data.SqlClient.SqlException e) { throw new Exception(e.Message); } finally { myCmd.Dispose(); myCn.Close(); } } 但这样容易被注入, 于是我做了以下改进: /**//// <summary> /// 用存储过程执行一句SQL语句,需要传入存储过程的名字 /// </summary> /// <param name="ProcName">存储过程的名字</param> public void dbExectSqlOnProc(string ProcName) { SqlConnection con = new SqlConnection(strConn); SqlCommand cmd = new SqlCommand(ProcName, con); cmd.CommandType = CommandType.StoredProcedure; try { con.Open(); cmd.ExecuteNonQuery(); } catch (System.Data.SqlClient.SqlException e) { throw new Exception(e.Message); } finally { cmd.Dispose(); con.Close(); } } 这样想执行一句SQL语句时就在数据库中写一个存储过程,然后再在后台给命令对象添加参数, 不管是几个参数,只需要在写方法和写存储过程时添加上就可以了。 但是写方法时初始化的(SqlParameter[] paras = new SqlParameter[2])paras 参数怎么传进去呢??? 呵呵,有点迷~~~早点睡了。 转载于:https://www.cnblogs.com/gengxiaochao/archive/2007/09/27/907342.html