在数据库中插入字符串值时出现sql错误.. [英] sql error when insert string value in database..

查看:435
本文介绍了在数据库中插入字符串值时出现sql错误..的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试插入

42"O/D X 36"O/D x 5''-00"lg.col.pipe Fabricated to drg.no. JPI-30368-B

这个字符串通过textBox,它给出了一个错误

this string through textBox, It''s give an error

Syntax error in string in query expression ''''42"O/D X 36"O/D x 5''-00"lg.col.pipe Fabricated to drg.no. JPI-30368-B''





我的代码是 - :





My Code is -:

using System;
using System.Windows.Forms;
using System.Data.OleDb;

namespace ForPrintPre
{
    public partial class Form2 : Form
    {
        OleDbConnection Conn;
        OleDbCommand Cmd;
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Cmd.CommandText = "insert into Table1 values('" + textBox1.Text + "')";
            Cmd.Connection = Conn;
            Cmd.ExecuteNonQuery();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            Conn = new OleDbConnection(@"Provider=microsoft.jet.oledb.4.0; Data Source=d:\PiyashData.mdb;");
            Conn.Open();
            Cmd = new OleDbCommand();            
        }
    }
}





先谢谢!!!



Thanks in Advance!!!

推荐答案

你好Jayanta,



看起来像引号单引号问题。

您需要确保在INSERT字符串中没有单引号(''),因为这会弄乱SQL查询。

这是攻击数据库最常用的方法之一,它是 SQL Injection





这里有一个关于如何使用参数的例子:



Hi Jayanta,

Looks like a quotation marks and single quotation problem.
You need to make sure that in your INSERT string you don''t have single quote ('') since that messes up the SQL query.
This is one of the most common ways to attack a DB, it''s SQL Injection


Here''s an example on how use parametes:

string sqlIns = "INSERT INTO table (name, information, other) VALUES (@name, @information, @other)";

db.Open();
try
{
SqlCommand cmdIns = new SqlCommand(sqlIns, db.Connection);
cmdIns.Parameters.Add("@name", info);
cmdIns.Parameters.Add("@information", info1);
cmdIns.Parameters.Add("@other", info2);
cmdIns.ExecuteNonQuery();
cmdIns.Dispose();
cmdIns = null;
}
catch(Exception ex)
{
throw new Exception(ex.ToString(), ex);
}
finally
{
db.Close();
}









干杯,

Edo





Cheers,
Edo


你应该使用 SqlParameter 而不是像你那样构建SQL。阅读文档 [ ^ ]并更改代码以使用参数。这需要正确引用并因此阻止SQL注入。
You should use SqlParameter rather than constructing SQL like you have done. Read the documentation[^] and change your code to use parameters. This takes care of properly quoting and thus preventing SQL injection.


edo是正确的 - 问题在于使用您需要插入的字符串中的引号。



最简单的解决方案是参数查询



edo is correct - the problem is in the use of quotes in the string you need to insert.

The easiest solution is to parameterise the query

Cmd.CommandText = "insert into Table1 values(@myString)";
cmd.Parameters.Add("@myString", SqlDbType.String).Value = textBox1.Text;


这篇关于在数据库中插入字符串值时出现sql错误..的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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