2013-02-18 25 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