Solved

Escaping Single Quote in C# for the string inserted into SQL Server Database

Posted on 2010-09-23
7
1,071 Views
Last Modified: 2012-06-21
I am trying to use the Replace method in the C# code behind to escape single quotes (change it to double quotes). However, when the stored proc SaveMktMessForGivenProductType is run, the data is incorrectly inserted with double quotes rather than a single quote. I replaced the single quote to double quote in order to escape it and avoid erroring in SQL script, not for it to be inserted with the replaced extra quote within the database. Please see the code section and see if you can find a reason why the data is inserted with double quotes. Please help.
dsMktMessage = rdg.GetMktMessForGivenProductType("GetMktMessForGivenProductType", _ProductTypeID, "ProductTypeID", _HandheldIDMktMess, "HandheldID");

                        

                        dsMktMessage.Tables[0].TableName = MKTMESSAGING;



                        if (dsMktMessage.Tables[MKTMESSAGING].Rows.Count > 0)

                        {

                            _MktMessageOrigText = dsMktMessage.Tables[MKTMESSAGING].Rows[0]["MktMessage"].ToString();

                            _KeySellPtOrigText = dsMktMessage.Tables[MKTMESSAGING].Rows[0]["KeySellPt"].ToString();

                        }



                        rdg.SaveMktMessForGivenProductType("SaveMktMessForGivenProductType", _ProductTypeID, _HandheldIDMktMess, _MktMessageText.Replace("'", "''"), _KeySellingPointsText.Replace("'", "''"), _MktMessageOrigText.Replace("'", "''"), _KeySellPtOrigText.Replace("'", "''"));

Open in new window

0
Comment
Question by:skaleem1
7 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
Comment Utility
How are you writing to the database, are you parameterised queries? If you are then you don't need to escape the apostrophe, it will be done automatically.
0
 
LVL 33

Expert Comment

by:Todd Gerbert
Comment Utility
You should use parameters instead of trying to escape the quotes... rdg.SaveMktMessForGivenProductType() is your method, and in it using a SqlConnection/SqlCommand?  If so, then you could use a method like below and pass in strings with single quotes without needing to escape them.

static void SaveRecordToDbTest(string field1, string field2)

{

	SqlConnection connection = new SqlConnection("Connection String");

	SqlCommand command = connection.CreateCommand();



	command.CommandText = "INSERT INTO TableName (FieldNameOne,FieldNameTwo) VALUES(@FieldOneValue, @FieldTwoValue)";

	command.Parameters.AddWithValue("@FieldOneValue", field1).DbType = DbType.String;

	command.Parameters.AddWithValue("@FieldTwoValue", field2).DbType = DbType.String;

	command.ExecuteNonQuery();



	command.Dispose();

	connection.Close();

	connection.Dispose();

}

Open in new window

0
 
LVL 1

Author Comment

by:skaleem1
Comment Utility
This is the method I am calling:

public void SaveMktMessForGivenProductTypeAndHandheld(string StoredProcName, string ProductTypeID, string HandheldIDMktMess, string MktMessageText, string KeySellingPointsText, string MktMessageOrigText, string KeySellPtOrigText)
        {
            Database theDB = DatabaseFactory.CreateDatabase("AccessoriesConnectionString");
            theDB.ExecuteNonQuery(StoredProcName, new object[] { ProductTypeID, HandheldIDMktMess, MktMessageText, KeySellingPointsText, MktMessageOrigText, KeySellPtOrigText });
        }
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 1

Author Comment

by:skaleem1
Comment Utility
Using Enterprise Library 4.1
0
 
LVL 58

Expert Comment

by:cyberkiwi
Comment Utility
The only things I can think of

... if you mean double-quotes as in the "double quote", then it is contained in the data itself.

... if you mean double-quotes as in TWO x single-quotes, then SaveMktMessForGivenProductType may ALSO contain the replace-protect single-quotes. In which case you are doing it twice.
0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
Comment Utility
Well from your definition you appear to be using a stored procedure, so escaping the apostrophes shouldn't be necessary.
0
 
LVL 1

Author Closing Comment

by:skaleem1
Comment Utility
Thanks carl_tawn. I removed the replace method to escape single quote and the data is inserted as expected.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now