C# 如果包含撇号,如何插入数据?

C# 如果包含撇号,如何插入数据?,c#,sql-server,C#,Sql Server,实际上,我的任务是使用c#将csv文件加载到sql server中,所以我用逗号将其拆分。我的问题是,某些字段的数据包含撇号,我正在启动insert查询以将数据加载到sql中,因此它会给我这样的编码带来错误 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using Sys

实际上,我的任务是使用c#将csv文件加载到sql server中,所以我用逗号将其拆分。我的问题是,某些字段的数据包含撇号,我正在启动insert查询以将数据加载到sql中,因此它会给我这样的编码带来错误

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

namespace tool
{
    public partial class Form1 : Form
    {
        StreamReader reader;
        SqlConnection con;
        SqlCommand cmd;
        int count = 0;
        //int id=0;
        FileStream fs;
        string file = null;
        string file_path = null;
        SqlCommand sql_del = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog file1 = new OpenFileDialog();
            file1.ShowDialog();
            textBox1.Text = file1.FileName.ToString();
            file = Path.GetFileName(textBox1.Text);
            file_path = textBox1.Text;
            fs = new FileStream(file_path, FileMode.Open, FileAccess.Read);

        }

        private void button2_Click(object sender, EventArgs e)
        {

               if (file != null )
                  {
                    sql_del = new SqlCommand("Delete From credit_debit1", con);
                    sql_del.ExecuteNonQuery();
                    reader = new StreamReader(file_path);
                    string line_content = null;
                    string[] items = new string[] { };
                    while ((line_content = reader.ReadLine()) != null)
                    {
                        if (count >=4680)
                        {
                            items = line_content.Split(',');
                            string region = items[0].Trim('"');
                            string station = items[1].Trim('"');
                            string ponumber = items[2].Trim('"');
                            string invoicenumber = items[3].Trim('"');
                            string invoicetype = items[4].Trim('"');
                            string filern = items[5].Trim('"');
                            string client = items[6].Trim('"');
                            string origin = items[7].Trim('"');
                            string destination = items[8].Trim('"');
                            string agingdate = items[9].Trim('"');
                            string activitydate = items[10].Trim('"');

                            if ((invoicenumber == "-") || (string.IsNullOrEmpty(invoicenumber)))
                            {
                               invoicenumber = "null";

                            }
                            else
                            {
                                invoicenumber = "'" + invoicenumber + "'";
                            }


                            if ((destination == "-") || (string.IsNullOrEmpty(destination)))
                            {
                                destination = "null";

                           }
                            else
                            {
                               destination = "'" + destination + "'";
                            }

                            string vendornumber = items[11].Trim('"');

                            string vendorname = items[12].Trim('"');

                            string vendorsite = items[13].Trim('"');

                            string vendorref = items[14].Trim('"');

                            string subaccount = items[15].Trim('"');

                            string osdaye = items[16].Trim('"');

                            string osaa = items[17].Trim('"');


                            string osda = items[18].Trim('"');

                            string our = items[19].Trim('"');


                            string squery = "INSERT INTO credit_debit1" +
                                          "([id],[Region],[Station],[PONumber],[InvoiceNumber],[InvoiceType],[FileRefNumber],[Client],[Origin],[Destination], " +
                                          "[AgingDate],[ActivityDate],[VendorNumber],[VendorName],[VendorSite],[VendorRef],[SubAccount],[OSDay],[OSAdvAmt],[OSDisbAmt], " +
                                          "[OverUnderRecovery] ) " +
                                          "VALUES " +
                                          "('" + count + "','" + region + "','" + station + "','" + ponumber + "'," + invoicenumber + ",'" + invoicetype + "','" + filern + "','" + client + "','" + origin + "'," + destination + "," +
                                          "'" + (string)agingdate.ToString() + "','" + (string)activitydate.ToString() + "','" + vendornumber + "',' " + vendorname + "',' " + vendorsite + "',' " + vendorref + "'," +
                                         "'" + subaccount + "','" + osdaye + "','" + osaa + "','" + osda + "','" + our + "') ";

                            cmd = new SqlCommand(squery, con);
                            cmd.CommandTimeout = 1500;

                            cmd.ExecuteNonQuery();

                        }
                        label2.Text = count.ToString();

                        Application.DoEvents();
                        count++;


                    }


                    MessageBox.Show("Process completed");
                }
                else
                {
                    MessageBox.Show("path select");
                }
        }









        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            con = new SqlConnection("Data Source=192.168.50.200;User ID=EGL_TEST;Password=TEST;Initial Catalog=EGL_TEST;");
            con.Open();
        }
    }

}

vendername字段包含数据(MCCOLLISTER的传输),因此如何传递此数据在本例中使用或等效。有各种各样的教程可供选择。

你用这种方式构建sql语句真是太淘气了,圣诞老人今年肯定不会来看你了。按照您现在的方式执行查询会让您自己面临sql注入攻击,正如您在使用“”时发现的那样,无论是有意还是无意

您应该使用参数化查询字符串或存储过程

const string connString = "Data Source=localhost;Initial Catalog=OnlineQuiz;Integrated Security=True";

static void Main(string[] args)
{
    string query = string.Format("SELECT * FROM [User] WHERE name like @name");

    using (SqlConnection conn = new SqlConnection(connString))
    {
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            cmd.Parameters.AddWithValue("@name", "F%");

            conn.Open();
            using (SqlDataReader reader = cmd.ExecuteReader())
            {

                while (reader.Read())
                {
                    Console.WriteLine(reader.GetValue(1));
                }
            }
        }
    }
}

您需要通过添加第二个撇号来避开撇号:

vendorname = vendorname.Replace("'", "''");
免责声明:不使用参数编写原始SQL语句是危险的。理想情况下,您应该使用假定的参数编写完整的SQL insert语句,而不是将值直接连接到字符串中,而是将其作为参数传入:

string parameterizedSQL = "insert into credit_debit1 (id,region,station) values (@count, @region,@station)";

SqlCommand cmd = new SqlCommand(parameterizedSQL, con);
cmd.Parameters.Add("@count", SqlDbType.Int).Value = count;
cmd.Parameters.Add("@region", SqlDbType.VarChar).Value = region;
cmd.Parameters.Add("@station", SqlDbType.VarChar).Value = station;
cmd.ExecuteNonQuery();

通过添加撇号构建一个查询,使其看起来不正确,并且仍然存在问题。是的,但不要告诉我,您的答案将花费更少的时间来实现,或者也不会出现错误。您的答案甚至不包括insert或存储过程调用。您可以轻松地将select查询替换为insert查询。您的建议是错误的,因为它可能受到sql注入攻击,而使用参数化查询则不是。通过字符串连接编写sql并没有错。这可能很危险,但肯定有效。我的答案写得更快,符合现有的代码,并且不宣扬“淘气”。不,这是绝对错误的。您可以为参数化查询构建字符串,并正确地插入参数。在没有参数化查询的情况下,为正确检查和清除注入该字符串中的所有值而必须编写的代码量将远远超过正确注入参数所需的额外几行。这并没有回答问题。是的,“F%”很可能是“O”。。。更重要的是,它演示了如何使用参数化查询编写它。实际上,
AddWithValue
可以影响计划的重用,因为它使用该值来推断参数长度。最好手动定义arg,明确说明正确的长度。