Microsoft KB Archive/311021

= HOW TO: Manage Quotation Marks in Concatenated SQL Literals by Using ADO.NET and Visual C# .NET =

Article ID: 311021

Article Last Modified on 3/9/2007

-

APPLIES TO


 * Microsoft ADO.NET 1.0
 * Microsoft ADO.NET 1.1
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft .NET Framework Class Libraries 1.0
 * Microsoft .NET Framework Class Libraries 1.1
 * Microsoft SQL Server 2000 Standard Edition
 * Microsoft SQL Server 2000 64-bit Edition
 * Microsoft SQL Server 7.0 Standard Edition

-



This article was previously published under Q311021



For a Microsoft Visual Basic .NET version of this article, see 311023.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.Web.SessionState
 * System.Text
 * System.Data.SqlClient

IN THIS TASK
SUMMARY Requirements Create a Visual C# .NET Console Application Samples That Manage Quotation Marks in Concatenated SQL Statements
 * Sample That Uses SQL Server
 * Sample That Uses Access

Troubleshooting REFERENCES



SUMMARY
This article demonstrates how you can manage quotation marks in string values when you concatenate SQL statements. The article provides a sample solution that uses the Sql managed provider (Microsoft SQL Server) and provides a Microsoft Access sample that uses the Microsoft OLE DB Provider and related data access classes.

back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:
 * Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or Microsoft Windows XP Professional
 * Microsoft .NET Framework
 * Microsoft Access
 * Microsoft SQL Server

back to the top

Create a Visual C# .NET Console Application
These steps demonstrate how to create a new Visual C# .NET Console Application named QuoteDemo.
 * 1) Start Microsoft Visual Studio .NET.
 * 2) On the File menu, point to New, and then click Project.
 * 3) In the New Project dialog box, click Visual C# Projects under Project Types, and then click Console Application under Templates.
 * 4) In the Name text box, type QuoteDemo.
 * 5) Click OK to open the project.

back to the top

Samples That Manage Quotation Marks in Concatenated SQL Statements
In this section, you create a sample that demonstrates how to use the Replace method of the String class. This sample replaces single quotation marks with two adjacent single quotation marks to make sure that the data is formatted correctly when you concatenate values for a SQL statement. The code in this demonstration uses a SQL INSERT statement on the Employees table of the Northwind database.

Both of the SQL Server and the Access samples in this article reference the FixString method. You must include this method for either sample to function properly. To do this, add the following method to the default Class1.cs file: private static string FixString(string SourceString, string StringToReplace, string StringReplacement) {   SourceString = SourceString.Replace(StringToReplace, StringReplacement); return(SourceString); } By default, this class is added to the project when you use Visual Studio .NET. The preceding method uses the Replace method of the String object. You can use this method to replace characters with other choices. The input parameters include the original string (SourceString), the string that you want to replace (StringToReplace), and the string that you want to use (StringReplacement).

NOTE: For more complex string substitutions, see the following Microsoft .NET Class Library documentation:

StringBuilder Class

http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemTextStringBuilderClassTopic.asp?frame=true

back to the top

Sample That Uses SQL Server
  Add the System.Data.SqlClient and the System.Text namespace references to the class. If you are using Visual Studio .NET, the resulting namespace listing appears as follows: using System; using System.Data.SqlClient; using System.Text;   Add the following method to the class: private static void RunSqlDemo {   //Create a variable to hold the last name and the first name. string fname = &quot;Susan&quot;; string lname = &quot;&quot;;

Console.Write(&quot;Type Last Name (SQL Server Sample): &quot;); lname = Console.ReadLine;

//Call FixString to replace a single quotation mark with two //adjacent single quotation marks. lname = FixString(lname, &quot;'&quot;, &quot;''&quot;); Console.WriteLine(&quot;Modified value: &quot; + lname);

//Although the fname variable in this sample is fine, //run Replace on this variable also. fname = FixString(fname, &quot;'&quot;, &quot;''&quot;);

//Use a StringBuilder object to build the SQL statement. StringBuilder sb = new StringBuilder; sb.Append(&quot;INSERT INTO Employees(LastName, FirstName) Values( '&quot;);   sb.Append(lname);    sb.Append(&quot;','&quot;);    sb.Append(fname);    sb.Append(&quot;')&quot;);

//Present the SQL statement to the console, and include the //modified values. Console.WriteLine(&quot;SQL string: &quot; + sb.ToString);

//Create the connection string. string myConStr = &quot;Server=localhost;Database=Northwind;UID=myUserID;PWD=myPassword&quot;; SqlConnection myConn = new SqlConnection(myConStr); SqlCommand myCmd = new SqlCommand(sb.ToString, myConn);

try {       //Open the connection. myConn.Open; myCmd.ExecuteNonQuery; Console.WriteLine(&quot;Values inserted into table (SQL Server Sample)&quot;); }   finally {       myConn.Close; } } NOTE: Modify the SQL Server connection string for your environment.   To call the RunSqlDemo method, add the following code to Main: RunSqlDemo;  On the File menu, click Save All to save the solution. On the Build menu, click Build Solution. On the Debug menu, click Start Without Debugging to run the application. When you are prompted to request a value for the last name, type the name O'Conner, and then press ENTER.

You receive a message that includes the following information:

<ul> How the FixString method modifies the last name value.</li> How the modified string appears in the SQL statement.</li> Confirmation that the value is added to the database.</li></ul>

Notice that the last name is modified to O''Conner. SQL Server interprets the two adjacent single quotation marks as an embedded single quotation mark.</li></ol>

back to the top

Sample That Uses Access
<ol>  Add the System.Data.OleDb and the System.Text namespace references to the class. If you are using Visual Studio .NET, and if you already created the SQL Server sample in the previous section, the resulting namespace listing for your class file appears as follows: using System; using System.Data.SqlClient; using System.Text; using System.Data.OleDb; </li>  Add the following method to the class: private static void RunAccessDemo {   //Create a variable to hold the last name and the first name. string fname = &quot;Susan&quot;; string lname = &quot;&quot;;

Console.Write(&quot;Type Last Name (Access Sample): &quot;); lname = Console.ReadLine;

//Call FixString to replace a single quotation mark with two //adjacent single quotation marks. lname = FixString(lname, &quot;'&quot;, &quot;''&quot;); Console.WriteLine(&quot;Modified value: &quot; + lname);

//Although the fname variable in this sample is fine, //run Replace on the variable also. fname = FixString(fname, &quot;'&quot;, &quot;''&quot;);

//Use a StringBuilder object to build the SQL statement. StringBuilder sb = new StringBuilder; sb.Append(&quot;INSERT INTO Employees(LastName, FirstName) Values( '&quot;);   sb.Append(lname);    sb.Append(&quot;','&quot;);    sb.Append(fname);    sb.Append(&quot;')&quot;);

//Present the SQL statement to the console, and include the //modified values. Console.WriteLine(&quot;SQL string: &quot; + sb.ToString);

//Create the connection string. string myConStr = &quot;Provider=Microsoft.Jet.OLEDB.4.0;&quot; + @&quot;Data Source=C:\MyDatabases\NWIND.MDB&quot;;

OleDbConnection myConn = new OleDbConnection(myConStr); OleDbCommand myCmd = new OleDbCommand(sb.ToString, myConn);

try {       //Open the connection. myConn.Open; myCmd.ExecuteNonQuery; Console.WriteLine(&quot;Values inserted into Employees table! (Access Sample)&quot;); }   finally {       myConn.Close; } } NOTE: Modify the connection string to properly reflect your environment. </li>  To call the RunAccessDemo method, add the following code to Main: RunAccessDemo; NOTE: If you followed the steps to run the previous SQL Server sample, and if you do not want to run the RunSqlDemo method again, you can comment out the call to the RunSqlDemo method in Main. </li> On the File menu, click Save All to save the solution.</li> On the Build menu, click Build Solution.</li> On the Debug menu, select Start Without Debugging to run the application.</li> When you are prompted to request a value for the last name, type the name O'Conner, and then press ENTER.

You receive a message that includes the following information: <ul> How the FixString method modifies the last name value.</li> How the modified string appears in the SQL statement.</li> Confirmation that the value is added to the database.</li></ul> </li></ol>

back to the top

Troubleshooting
<ul> If you do not replace the single quotation mark with two adjacent single quotation marks, you receive a syntax error that is similar to either of the following error messages:

System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'Conner'. Unclosed quotation mark before the character string ')

-or-

Unhandled Exception: System.Data.OleDb.OleDbException: Syntax Error (missing operator) in query expression ''O'Conner', 'Susan')'

</li> When you use the Access sample in this article, if you press ENTER without providing any input when you are prompted, you may receive the following error message (or a similar one):

Field  cannot be a zero-length string.

Access interprets an empty string field as a zero-length string. This error occurs if the AllowZeroLength property of the database field is not set to Yes. See the REFERENCES section for more information.</li></ul>

back to the top

<div class="references_section">