這是我編寫select語句來檢查數據庫中是否有值的方法。使用SqlDataReader將值插入到SQL Server表中
bool userIsPresent=false;
string sqlQuery = string.Format("SELECT * FROM Person WHERE Name = '{0}'", name);
SqlCommand s = new SqlCommand(sqlQuery, con);
con.Open();
SqlDataReader sqlread = s.ExecuteReader();
userIsPresent = sqlread.HasRows;
con.Close();
但現在我需要一些值保存到數據庫中。我怎樣才能做到這一點 ?我不認爲我應該使用SqlDataReader
,那麼如何保存並確認數據是否保存到數據庫?
public static bool saveToDb(string name1,string nam2, DateTime dat)
{
bool ok=false;
string sqlQuery = string.Format("INSERT into NumbersTable values ('{0}', '{1}','{2}')",name1,nam2,dat);
SqlCommand s = new SqlCommand(sqlQuery, con);
con.Open();
SqlDataReader sr = s.ExecuteReader(); // MIGHT BE WRONG
ok = sr.HasRows;
con.Close();
return ok;
}
請注意,'string.Format'不會阻止你進行sql注入攻擊。改用SQL參數! – 2013-02-18 08:08:02