How to insert a string with ( ' ) in to the sql database?

I'm pretty sure you don't use SQL parameters:

using (SqlCommand myCommand = new SqlCommand(
    "INSERT INTO table (text1, text2) VALUES (@text1, @text2)")) {

    myCommand.Parameters.AddWithValue("@text1", "mother's love");
    myCommand.Parameters.AddWithValue("@text2", "father's love");
    //...

    myConnection.Open();
    myCommand.ExecuteNonQuery();
    //...
}

Use named parameters and the SqlParameter.

From http://www.dotnetperls.com/sqlparameter

class Program
{
    static void Main()
    {
        string dogName = "Fido";  // The name we are trying to match.

        // Use preset string for connection and open it.
        string connectionString = 
            ConsoleApplication1.Properties.Settings.Default.ConnectionString;

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            // Description of SQL command:
            // 1. It selects all cells from rows matching the name.
            // 2. It uses LIKE operator because Name is a Text field.
            // 3. @Name must be added as a new SqlParameter.
            using (SqlCommand command = 
               new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE @Name", connection))
            {
                // Add new SqlParameter to the command.
                command.Parameters.Add(new SqlParameter("Name", dogName));

                // Read in the SELECT results.
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    int weight = reader.GetInt32(0);
                    string name = reader.GetString(1);
                    string breed = reader.GetString(2);
                    Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}", weight, name, breed);
                }
            }
        }
    }
}

Although, you could replace all ' characters in the string with two ' characters (''), it's not a good idea. Because of this issue, and many other reasons (such as avoiding SQL-injection attacks), you definitely should be using named parameters rather than adding the values to your insert statement by concatenating them directly into the string. For instance:

command.CommandText = "Insert into tblDesEmpOthDetails (EmpID, Interviewnotes) values (@EmpId, @Interviewnotes)";
command.Parameters.AddWithValue("EmpId", EmpId);
command.Parameters.AddWithValue("Interviewnotes", Interviewnotes);

Tags:

C#

Sql Server