我有数据库功能,可以根据不同的条件选择数据。有两种可能的方法来实现这一点。第一的
public string select(string name)
{
string s = null;
query = "select * from tablename where name=@name";
con.Open();
com=new SqlCeCommand(query,con);
com.Parameters.AddWithValue("@name",name);
sdr=com.ExecuteReader();
while (sdr.Read())
{
s = sdr.GetString(0);
}
return s;
}
在这种方法中,我需要为查询中的小变化编写不同的函数,例如 order by ,地址代替 name 或 where query 中的多个参数,top 20 等。但是这种方法在 sql 注入方面是安全的。第二
public string select(string query)
{
string s = null;
con.Open();
com=new SqlCeCommand(query,con);
sdr=com.ExecuteReader();
while (sdr.Read())
{
s = sdr.GetString(0);
}
return s;
}
在第二种方法中,我在带有值的函数参数中传递数据库查询,因此我不需要也不需要com.Parameters.AddWithValue("@name",name);
为选择查询的更改编写不同的函数。查询中的参数值由代码而不是用户给出。在这种方法中是否可以进行 sql 注入,因为用户没有为参数提供输入。
哪一个既安全又高效,因为我的应用程序无法承受数据丢失。