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

时间:2010-04-24 05:59:53

标签: c# sql-server

实际上我的任务是使用c#将csv文件加载到sql server中,所以我用逗号分割它我的问题是某些字段的数据包含撇号和im触发插入查询以将数据加载到sql中所以它给出错误我的编码就像那样< / p>

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'S TRANSPORTATION)以及如何传递此数据

3 个答案:

答案 0 :(得分:6)

使用prepared statements,在这种情况下为SqlParameterCollection.AddWithValue或等效。有很多教程可供选择。

答案 1 :(得分:-2)

你非常顽皮地建立你的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));
                }
            }
        }
    }
}

答案 2 :(得分:-2)

你需要通过添加第二个撇号来逃避撇号:

vendorname = vendorname.Replace("'", "''");

免责声明:在不使用参数的情况下编写原始SQL语句是危险的。理想情况下,您应该编写带有假定参数的完整SQL插入语句,而不是将值直接连接到字符串中,将其作为参数传递:

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();