Inserting a String with Double Quotes into a Table

How to add a string containg a double quote to a sql database?

I tried adding the string by escaping the double quote but that didn't work. The only way I could add the string is by using PreparedStatement instead of a Statement class.

String string = "abc\"abc";
String sql = "INSERT INTO tableName VALUES(?)";

connection = DriverManager.getConnection(DB_URL, USER, PASS);
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, string);
preparedStatement.executeUpdate();

This code segment successfully adds the string containing the double quote into the database.

Insert simple + double quote MySQL

You can use ' as string delimiters and backslash to escape special chars:

Insert into name values ('it\'s \"string\"') 

SQL Single quote and double quote inserting values

Always use single quote, and double single quote when needed.

('Where I''m Calling From: Selected Stories', 'Raymond', 'Carver', 1989, 12, 526)

How to insert string containing single or double quotes

If you use properly parameterized statements, you shouldn't need to worry about it. Something like this (though please don't learn C# techniques from me):

string sql = @"UPDATE dbo.table SET col = @p1 WHERE ...;";
string myString = @"hello'foo""bar";

SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@p1", SqlDbType.VarChar, 30).Value = myString;

(Though you really should be using stored procedures.)

If you are building your strings manually (which you really, really, really shouldn't be doing), you need to escape string delimiters by doubling them up:

INSERT dbo.tbl(col) VALUES('hello''foo"bar');

Single and double quote issue in SQL insert

When building the INSERT, use single quotes in the outside and the problem with double quotes is solved.

To fix the problem with single quotes, replace ' by ''.

How to add one double-quotes () to string?

This is how:

string mystring = "We use \"a laser\"";

BUT! Since you are trying to form an sql query, you shouldn't do this yourself. You need to use sql parameters that will protect you from sql injection.

Here is a short lesson about sql parameters: http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06

how to insert the value having double quotes in the database?

Have you tried using prepared statements? This way you don't have to worry about adding the quotes in the values section; you use question marks instead as place holders.

You could then use addslashes to escape any double/single quotes when you pass your variables/strings to the execute method.

You didn't mention which database you're using, so I'm assuming MySQL?

Here is the PHP manual on prepared statements:

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php



Related Topics



Leave a reply



Submit