将值插入使用SqlDataReader的SQL Server表 [英] Insert values into SQL Server table using SqlDataReader
本文介绍了将值插入使用SqlDataReader的SQL Server表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我如何写作SELECT语句来检查,如果有一个在数据库中的值。
布尔userIs present = FALSE;
字符串的SQLQuery =的String.Format(SELECT * FROM WHERE人名称='{0}',名);的SqlCommand S =新的SqlCommand(sqlquery的,CON);
con.Open();SqlDataReader的sqlread = s.ExecuteReader();
userIs present = sqlread.HasRows;
con.Close();
但现在我需要一些值保存到数据库中。我怎样才能做到这一点?我不认为我应该用 SqlDataReader的
,所以我怎么可以保存并确认是否将数据保存到数据库?
公共静态布尔saveToDb(字符串名称1,串nam2,日期DAT)
{
布尔OK = FALSE;
字符串的SQLQuery =的String.Format(INSERT INTO NumbersTable VALUES('{0},{1},{2}),名称1,nam2,DAT); 的SqlCommand S =新的SqlCommand(sqlquery的,CON); con.Open();
SqlDataReader的SR = s.ExecuteReader(); //可能是错的
OK = sr.HasRows; con.Close();
返回OK;
}
解决方案
您需要的的ExecuteNonQuery 在数据库中插入记录。
s.ExecuteNonQuery();
的(使用参数化查询以prevent SQL注入)的
This is how I wrote a select statement to check if there's a value in the database.
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();
But now I need to save some values into the database. How can I do this ? I don't think I should use SqlDataReader
, so how can I save and confirm if the data is saved to the database?
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;
}
解决方案
You need ExecuteNonQuery for inserting records in the database.
s.ExecuteNonQuery();
(Use Parameterized query to prevent SQL Injection)
这篇关于将值插入使用SqlDataReader的SQL Server表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文