user2499974
user2499974

Reputation: 379

insert special character into SQL Server 2008 database from c#

i want to insert special character into sqlserver 2008 database. for example ('/@#&*$) etc.

i have tried the following code but it remove these string from the orignal string.

string[] arrtime = postingtime.Split(',');
                            string sss = arrtime[1];
                            string sss1 = "EDT";
                            bool first2 = true;
                            string s33 = Regex.Replace(sss, sss1, (m) =>
                            {
                                if (first2)
                                {
                                    first2 = false;
                                    return "";
                                }

                                return sss1;

                            });

But i didnt want to remove these string from the orignal string...because i want to insert a franch language data and removal of these special character will change the meaning of sentence.

my insert query is:

  cn.Open();
        adp.InsertCommand = new SqlCommand("insert into ttt values('r=DE'S''C/pa-ge=1/$@')", cn);
        adp.InsertCommand.ExecuteNonQuery();
        cn.Close();

when i click on insert button then it gives error(datatype error). my problem is , to insert string with special characters not to remove these character. i want to pass these characters to our sql server 2008 from c# application. thanx in advance

Upvotes: 0

Views: 4298

Answers (3)

Damith
Damith

Reputation: 63065

Use parameters

adp.InsertCommand = new SqlCommand("insert into ttt values(@p1)", cn);
adp.InsertCommand.Parameters.Add(new SqlParameter("@p1", SqlDbType.NVarChar)).Value = "r=DE'S''C/pa-ge=1/$@";

Upvotes: 2

Ravi Gadag
Ravi Gadag

Reputation: 15861

Your Insert query vunlerable to SQL injections.. Try using SqlParameters. and in SQLServer User NVarchar datatype.

using (SqlConnection con = new SqlConnection(dc.Con))
            {
                using (SqlCommand cmd = new SqlCommand("insert into ttt values(@paramValue)", con))
                {

                    cmd.Parameters.AddWithValue("@paramValue", "r=DE'S'C@4593§$%");
                    con.Open();
                    cmd.ExecuteNonQuery();
                }

            }

Upvotes: 1

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Use parameterized queries like this:

using (SqlConnection cn = new SqlConnection(...))
{
    cn.Open();

    using (SqlCommand cmd = new SqlCommand("insert into ttt values (@testvalue)", cn))
    {
        cmd.Parameters.AddWithValue("@testValue", "r=DE'S'C@4593§$%");
        cmd.ExecuteNonQuery();
    }
}

Upvotes: 3

Related Questions