tags:

views:

285

answers:

3

Actally my task is load csv file into sql server using c# so i have split it by comma my problem is that some field's data contain apostrop and i m firing insert query to load data into sql so its give error my coding like that

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 field contain data (MCCOLLISTER'S TRANSPORTATION) so how to pass this data

+5  A: 

Use prepared statements, in this case SqlParameterCollection.AddWithValue or equivalent. There are a variety of tutorials available for this.

Matthew Flaschen
Actually, `AddWithValue` can impact plan re-use, since it uses the value to infer the arg-length. Better to define the arg manually, explicitly stating the *correct* length.
Marc Gravell
A: 

You are very naughty for building your sql statements that way, Santa Claus is definitely not going to visit you this year. Doing queries the way you are is opening yourself to sql injection attacks, intentional and unintentional as you've discovered with the '.

You should use parameterized query strings or stored procedures.

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));
                }
            }
        }
    }
}
Felan
Does not answer the question.
Jeff Meatball Yang
Yes it does, "F%" could easily be "O'%" ... more importantly it demonstrates how to write it using a parameterized query.
Felan
A: 

You need to escape the apostrophe by adding a second apostrophe:

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

Disclaimer: Writing a raw SQL statement without using parameters is dangerous. Ideally, you should write a full SQL insert statement with assumed parameters, and instead of concatenating the value directly into the string, pass it in as a parameter:

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();
Jeff Meatball Yang
Building a query like he isn't made right by adding an apostrophe and is still suspectible to problems.
Felan
Yes, but don't tell me your answer will take less time to implement, or will also be bug-free. Your answer doesn't even include an insert or sproc call.
Jeff Meatball Yang
You can easily replace the select query with insert query. And what you propose is wrong because it is suspectible to sql injection attacks, using a parameterize query is not.
Felan
Writing sql via string concatenation is NOT WRONG. It may be dangerous, but it definitely works. My answer is faster to write, fits the existing code, and does not preach about being "naughty".
Jeff Meatball Yang
No it is absolutely wrong. You can build a string for a parameterized query and inject the parameters properly. The amount of code you would have to write to properly check and scrub all the values you inject into that string without a parameterized query will far exceed the extra couple of lines it takes to inject parameters properly.
Felan
You have obviously been brainwashed by the best practice police. Best practices are used as guidelines, not rules. If you asked why your TV is fuzzy, and one person told you that you should rewire your house a certain way to reduce interference, and another said to fiddle with the antenna a little, which would you consider more helpful?
Jeff Meatball Yang
Doing queries like that is throwing live unshielded wires on the floor of your house and not caring because you are careful enough to avoid them. And he has already been zapped once by it.
Felan
Look at his code. He already has to parse his data. My answer may not mitigate the "injection attack" danger, but it is far from wrong - and your insistence to the contrary is only showing that you do not take the time to understand a problem before doling out condescending, generic, and irrelevant advice.
Jeff Meatball Yang
Thanks a lot it's working but i inclued one thing more myMatch = System.Text.RegularExpressions.Regex.Match(vendorname,@"'"); if (myMatch.Success) { vendorname = vendorname.Replace("'", "''"); }
angel ansari
The problem is that building query strings like that is very suspectible to the very problem that caused him to create this post in the first place. That you feel the need to attack me is no reflection on me in the slightest.
Felan