Click here to Skip to main content
16,015,481 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using insert statement to insert values in sqlserver from excel sheet.eg.
+ row["id"].ToString()
+ "', '" + (row["Name"].ToString()).Trim()
+ "','" + (row["Headline"].ToString()).Trim()
+ "','" + row["Code"].ToString()
my excel sheet contains cells with values 's , " ' etc . One way is to replace them with blanks. Is there any other way in which I 'll be able to put this values in my sqlserver and how can I use one replace many workds with one character and don't want performance to degrade as there are around 7000 rows and 50 odd columns.
Posted
Comments
Philippe Mori 27-Aug-11 8:52am    
By the way if you manually create the request for each of the 7000 inserts, it might be a lot of overhead.

1 solution

Don't. What you are doing is called string concatenation, and it is (as you have seen) dangerous.
Instead, use a parametrized query:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("INSERT INTO myTable (myColumn1, myColumn2) VALUES (@ID, @NAME)", con))
        {
        com.Parameters.AddWithValue("@ID", row["id"]);
        com.Parameters.AddWithValue("@NAME", row["Name"].ToString()).Trim());
        com.ExecuteNonQuery();
        }
    }
This way you don't have to worry about the data content - it gets transfered with problems.
 
Share this answer
 
Comments
Philippe Mori 27-Aug-11 8:47am    
Effectively, a good suggestion. Never build a SQL request from unvalidated user strings as it is dangerous if someone why some SQL code (for example writting something like "DELETE FROM TableName" in your Excel cell) to maliciously corrupt your database.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900