我一直在编写一些简单的c#,我通常使用相同的类和函数来插入和获取数据库中的数据。
例如,这是我的功能:
public bool insert_and_ConfirmSQL(String Query, String comments)
{
bool success = false;
NpgsqlCommand cmd = new NpgsqlCommand();
NpgsqlConnection mycon = new NpgsqlConnection();
string connstring = String.Format("Server={0};Port={1}; User Id={2};Password={3};Database={4};timeout=1000;CommandTimeout=120;", tbHost, tbPort, tbUser, tbPass, tbDataBaseName);
mycon.ConnectionString = connstring;
cmd = mycon.CreateCommand();
cmd.CommandText = Query;
mycon.Open();
int temp = 0;
try
{
temp = cmd.ExecuteNonQuery();
success = true;
}
catch
{
if (mycon.State == ConnectionState.Open)
{
mycon.Close();
}
}
return success;
}
现在我知道这个查询不能安全地防止注入,我需要使用预准备语句。但是我不明白当我的每个查询都不同时我该如何处理?是否有一个“通用”函数插入任何查询并“准备”它?
答案 0 :(得分:3)
我建议你这样使用它,因为using语句负责连接& amp;命令
另外为了对sqlinjection采取安全措施,请使用SqlParameters(相当于Npgsl)来传递值
public void insert_and_ConfirmSQL(String Query,String comments) {
using(NpgsqlConnection mycon = new NpgsqlConnection())
{
using(NpgsqlCommand cmd = mycon.CreateCommand())
{
string connstring = String.Format("Server={0};Port={1}; User Id={2};Password={3};Database={4};timeout=1000;CommandTimeout=120;", tbHost, tbPort, tbUser, tbPass, tbDataBaseName);
mycon.ConnectionString = connstring;
cmd = mycon.CreateCommand();
cmd.CommandText = Query;
mycon.Open();
cmd.ExecuteNonQuery();
}
}
}
答案 1 :(得分:2)
如果您正在寻找一种更通用的执行插入/更新/删除的方法,可能以下是合适的(使用SqlClient但很容易适应NpgsqlClient):
public static object ExecuteActionProcedure(System.Data.CommandType CommandType, string CommandText, string[] Parameters, object[] Values)
{
try
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType;
cmd.CommandText = CommandText;
SqlParameter result = new SqlParameter();
result.ParameterName = "ResultValue";
result.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(result);
for (int i = 0; i < Parameters.Length; i++)
{
cmd.Parameters.AddWithValue(Parameters[i], Values[i]);
}
cmd.ExecuteNonQuery();
return (int)result.Value;
}
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
return null;
}
}
致电声明:
ExecuteActionProcedure(CommandType.StoredProcedure, "aspnet_SaveFullName", new string[] { "UserName", "FullName" }, new object[] { model.UserName, model.FullName });
请注意,您可以将此方法传递给包含参数和存储过程的SQL字符串。