如何将带有连字符(')的字符串插入数据库 [英] How to insert string with hyphen ( ' ) into database

查看:232
本文介绍了如何将带有连字符(')的字符串插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



我试图运行一个简单的INSERT查询,其中我用连字符(')传递一个字符串值。它抛出错误。如何使用连字符插入/更新字符串值。

前端:VB.net,C#

后端:MS-Access,Sql Server



表:



SID SName

1 ABC

2 DEF



问题:试图插入姓名= xyz的



代码:



Hello there,

I was trying to run a simple INSERT query in which i passed a string value with hyphen ( ' ). It throws error. How can i insert/Update a string value with hyphen.
Front-End : VB.net, C#
Back-End : MS-Access, Sql Server

Table :

SID SName
1 ABC
2 DEF

Problem : Trying to insert Name = xyz's

Code :

Dim Da As OleDbDataAdapter = New OleDbDataAdapter("Insert Into Student(SName) Values('" & txtUserName.Text & "')", Conn)
        Dim Ds As New DataSet
        Da.Fill(Ds)

推荐答案

使用参数化查询:

Use a parameterized query:
string test = "O' what happened?";

using (SqlConnection cnx = new SqlConnection(connectionString)) {
   cnx.Open();
   using (SqlCommand cmd = new SqlCommand("INSERT INTO [TestTable] ([TestField]) VALUES (@value)", cnx)) {
      cmd.Parameters.AddWithValue("@value", test);
      int result = cmd.ExecuteNonQuery();
   }
}





此外,它还具有将代码防御到SQL注入攻击的优势。

参数化查询应该在涉及用户输入的任何地方使用。

祝你好运:)



Moreover, it will have the advantage of bulletproofing your code to SQL injection attacks.
Parameterized queries should be used everywhere user input is involved.
Good luck :)


这篇关于如何将带有连字符(')的字符串插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆