Solved

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

Posted on 2010-09-23
7
1,137 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 33748072
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
ID: 33748137
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
ID: 33748144
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
Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 
LVL 1

Author Comment

by:skaleem1
ID: 33748160
Using Enterprise Library 4.1
0
 
LVL 58

Expert Comment

by:cyberkiwi
ID: 33748188
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
ID: 33748190
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
ID: 33748246
Thanks carl_tawn. I removed the replace method to escape single quote and the data is inserted as expected.
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
If you're a developer or IT admin, you’re probably tasked with managing multiple websites, servers, applications, and levels of security on a daily basis. While this can be extremely time consuming, it can also be frustrating when systems aren't wor…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…

724 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