/**/
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="cmdParms">参数数组</param>
/// <returns>影响的记录数</returns>
public int ExecuteSql( string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
}
}
}
private void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="cmdParms">参数数组</param>
/// <returns>影响的记录数</returns>
public int ExecuteSql( string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
}
}
}
private void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
在后台代码中:
protected
void
ImageButton1_Click(
object
sender, ImageClickEventArgs e)
{
SqlParameter[] parameters = {
new SqlParameter("@username", SqlDbType.NVarChar,256),
new SqlParameter("@realname", SqlDbType.VarChar,250)
};
parameters[0].Value = "sea";
parameters[1].Value = "gxc";
sdh.ExecuteSql("INSERT INTO [TFM].[dbo].[UserInfo] ([UserName] ,[RealName]) VALUES (@username ,@realname)", parameters);
Response.Write("<script>alert('添加成功!');</script>");
}
{
SqlParameter[] parameters = {
new SqlParameter("@username", SqlDbType.NVarChar,256),
new SqlParameter("@realname", SqlDbType.VarChar,250)
};
parameters[0].Value = "sea";
parameters[1].Value = "gxc";
sdh.ExecuteSql("INSERT INTO [TFM].[dbo].[UserInfo] ([UserName] ,[RealName]) VALUES (@username ,@realname)", parameters);
Response.Write("<script>alert('添加成功!');</script>");
}