SUMMARY
Use this step-by-step guide to format a string if there is a quotation mark in a member of the connection string.
back to the top
Description of the Technique
The sample explains how to format a password that includes a quotation mark. Without the proper formatting, the compiler will display a build error, similar to the following:
Comma, ')' , or a valid expression continuation expected.
Invalid Delimiter
Name 'ConnectionObject' is not declared.
If you use a single quotation mark in a password, you do not have to include the escape character for the single quotation mark. However, you need to include the escape character for the double quotation mark:
password=a'b // Not properly formatted.
password=\"a'b\" // Properly formatted.
If you use a double quotation mark in your password, you have to use the escape character. However, you need to include single quotation marks around the password value:
password=a"b // Not properly formatted.
password='a\"b' // Properly formatted.
back to the top
Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
- Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or Microsoft Windows NT 4.0 Server.
- Microsoft Visual Studio .NET.
- Microsoft SQL Server 7.0 or later.
This article assumes that you are familiar with the following topics:
- Visual Studio .NET.
- ADO .NET fundamentals and syntax.
back to the top
Create the Project and Add the Code
- Start Visual Studio .NET.
- In Visual C# .NET, create a new Windows application.
- Make sure that your project contains a reference to the System.Data namespace; add a reference if it does not.
- Add a Button control to Form1.
Change the Name property of the button to btnTest and the Text property to Test. - Add the following Using statements to the General Declarations section of Form1 so that you do not need to qualify declarations for the namespaces later in your code:
using System;
using System.Data;
using System.Data.SqlClient;
- Type or paste the following code in the btnTest Click event:
DataSet ds = new DataSet();
SqlConnection cn = new SqlConnection("server=myServer;user id=myUID;password=a"b;database=northwind");
SqlDataAdapter da = new SqlDataAdapter("select * from customers",cn);
da.Fill(ds, "customers");
- Modify the connection string for your environment. Notice the password has a quotation mark in it.
- Save your project. On the Debug menu, click Start to run your project. Notice the build errors if any appear.
- Change the connection string to the following:
("server=myServer;user id=myUID;password='a\"b';database=northwind")
- Save the project and then run it.
back to the top