如何向數據庫插入帶有單引號(')的字符串?


  • 用SQL語句往數據庫某字段(字符型)中插入字符串,但是當該字符串中帶有單引號(')時就會出錯!因為插入的字符串被從單引號處截斷,造成SQL語句的語法錯誤!
  •  

    我們在編程當中,經常會遇到在操作數據庫時,向表里插入帶有單引號的字符串。如果不作處理程序會報錯,下面看看我們是怎么的處理它的。

     

    用SQL語句往數據庫某字段(字符型)中插入字符串,但是當該字符串中帶有單引號(')時就會出錯!因為插入的字符串被從單引號處截斷,造成SQL語句的語法錯誤!

     

    解決方法:遍歷字符串,把一個(')換成兩個(' ')就可以了,在C#里,其實用str.Replace("'", "''");就OK了,這是因為SQL是用兩個單引號來代替一個單引號的,下面舉個例子:

     

    private void btAdd_Click(object sender, EventArgs e)
            {
                string chinese = this.txtChinese.Text.Trim();
                string english = this.txtEnglish.Text.Trim();
                if (chinese == "")
                {
                    MessageBox.Show("請輸入中文!");
                }
                else if (english == "")
                {
                    MessageBox.Show("請輸入英文!");
                }
                else
                {
                    oleConnection1.Open();
                    string sql = "Select * From info Where chinese='" + CheckString(chinese) + "' And english='" + CheckString(english) + "'";
                    this.oleCommand1.CommandText = sql;
                    if (null == oleCommand1.ExecuteScalar())
                    {
                        string sql1 = "Insert Into info(chinese,english) Values('" + CheckString(chinese) + "','" + CheckString(english) + "')";
                        oleCommand1.CommandText = sql1;
                        oleCommand1.ExecuteNonQuery();
                        MessageBox.Show("信息添加成功!", "提示");
                        this.txtChinese.Text = "";
                        this.txtEnglish.Text = "";
                    }
                    else
                    {
                        MessageBox.Show("信息添加失敗,中文和英文已經存在了!", "警告");
                        this.txtChinese.Text = "";
                        this.txtEnglish.Text = "";
                    }
                    oleConnection1.Close();
                }
            }

     

            private string CheckString(string str)
            {
                string returnStr = "";
                if (str.IndexOf("'") != -1) //判斷字符串是否含有單引號
                {
                    returnStr = str.Replace("'", "''");
                    str = returnStr;
                }
                return str;
            }

     

    這里為什么要用另一個變量(returnStr)來接收替換后的值呢?不然替換會失效,調用Replace()方法不能改變str本身,string對象雖然是引用類型,但它具有很多值類型特征,比較特殊。

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM