2013-02-18 77 views
0

这是我编写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; 
} 
+7

请注意,'string.Format'不会阻止你进行sql注入攻击。改用SQL参数! – 2013-02-18 08:08:02

回答

4

您需要ExecuteNonQuery在数据库中插入记录。

s.ExecuteNonQuery(); 

(使用Parameterized query防止SQL注入)

+0

你的意思是我应该离开'SqlDataReader sr =',并将'ExecuteReader'改成'ExectureNonQuery'? – 2013-02-18 08:03:33

+0

@sharonHwk,是 – Habib 2013-02-18 08:13:51

+0

@sharonHwk,不!哈比卜,你错了。 ExecuteNonQuery返回和查询所影响的整数行数。因此你不能使用SqlDataReader(因为你显然没有读任何东西!)。 – 2013-02-18 14:50:57

0

在代码中添加此:

con.open(); 
S.executeNonQuery(); 
+0

这段代码的问题是什么?它为什么会被低估?谁能告诉我原因? – coder 2013-02-18 09:19:12

+0

@llya lvanov那不是我的问题它是由someoneelse问的,我只是在我的答案中添加了executenonquery,但我的回答是downvoted。 – coder 2013-02-18 11:19:59

+0

好吧,公平点,我已经格式化了您的代码并将+1。我非常强烈地建议添加到你的回答评论关于**不**返回状态'布尔',但抓住低级别的SQL异常,并返回更高级别exceptuin。此外,使用sql参数,而不是'string.Format' – 2013-02-18 11:21:17

-1

只需要更正您现有的代码中的一些事情,无疑这会有所帮助对你来说:

public static bool executeMyQuery(string sqlQuery) 
     { 
     try 
     {  con.Open(); 
       SqlCommand s = new SqlCommand(sqlQuery, con); 
       s.ExecuteNonQuery(); 
       con.Close(); 
       return true; 
     } 
     catch() 
     { 
      return false; 
     } 

    And use the above function[executeMyQuery()] anywhere you want to insert like and check whether record is inserted or not like below: 

    bool isInserted = false; 
    // give dummy value or get it what u want to inser on name1,nam2,dat 
    string rawQuery = string.Format("INSERT into NumbersTable values ('{0}', '{1}','{2}')",name1,nam2,dat); 

    isInserted = myExecuteQuery(rawQuery); 

    if(isInserted) 
    { 
     // lblStatus i am taking only to make you understand 
     // lblStatus.text = "Record inserted succesfully"; 
    } 
    else 
    { 
     // lblStatus.text = "Record insertion failed"; 
    } 
+1

这种方法会阻止SQL注入吗? – 2013-02-18 08:34:03

+0

我只是举例说明他/她如何使用executenonquery来检查记录是否被插入,是的,这段代码不会阻止sql注入,我会稍后进行相应的编辑,想要给出答案,他/她得到的答案卡住:) – 2013-02-18 08:39:44

+0

有人可以解释为什么这个答案被拒绝投票吗?有没有更好的方法来做到这一点? – 2013-02-18 08:47:58

0

好吧所以y ou想要做的是插入到数据库中,而不是从中读取数据,因此您只需简单地对数据库执行sql查询,而不读取从数据库中选择的任何数据。为此,您需要使用ExecuteNonQuery语句而不是sqlDataReader。结果会看起来像这样

public static bool saveToDb(string name1, string nam2, DateTime dat) 
{ 
    bool ok = false; 
    string sqlQuery = "INSERT INTO NumbersTable VALUES (@name1, @nam2, @dat)"; 
    //This is the sql query we will use and by placing the @ symbol in front of words 
    //Will establish them as variables and placeholders for information in an sql command 
    //Next we create the sql command 
    SqlCommand cmd = new SqlCommand(sqlQuery, con); 
    //Here we will insert the correct values into the placeholders via the commands 
    //parameters 
    cmd.Parameters.AddWithValue("name1", name1); 
    //This tells it to replace "@name1" with the value of name1 
    cmd.Parameters.AddWithValue("nam2", nam2); 
    cmd.Parameters.AddWithValue("dat", dat); 
    //Finally we open the connection 
    con.Open(); 
    //Lastly we tell the sql command to execute on the database, in this case inserting 
    //the values 
    int i = cmd.ExecuteNonQuery(); 
    //Here we have the results of the execution stored in an integer, this is because 
    //ExecuteNonQuery returns the number of rows it has effected, in the case of this 
    //Insert statement it would effect one row by creating it, therefore i is 1 
    //This is useful for determining if your sql statement was successfully executed 
    //As if it returns 0, nothing has happened and something has gone wrong 
    con.Close(); 
} 

我希望这有助于,如果您需要其他任何东西随时问。

0

试试吧...这个代码将得到正确的消息..
1,名称2,DAT是列名在数据表中数据库

公共静态无效saveToDb()
{
string sqlQuery =“INSERT到NumbersTable(name1,name2,dat)values('Princee','Singhal','18/02/2012');
SqlCommand s = new SqlCommand(sqlQuery,con);
con .Open();
int i = s.Execut eNonQuery(); (i> = 1)
如果(i> = 1)
{
MessageBox.Show(“Record Inserted”);
}
其他
{
MessageBox.Show( “可能会出现一些问题Occure!”);
}
con.Close();
}

+0

我得到'0'。那么这是否意味着我的INSERT错误? – 2013-02-18 15:12:25

+0

当你得到我= 0 ...数据插入或不? – 2013-02-19 04:13:33