I want to store apostrophe in message box such as john's watch.It show erreor near 's - c#

Please help me to store apostrophe. I m creating a website (C#, .net, SQL Server) and want to have a message box for the users but the problem is that when I inserts any message such as John's it shows an error near ''s'.
Please tell me how could I store apostrophe in database
I used nvarchar, varchar and everything but failed to store apostrophe containing messages.
A general solution is to write message with double apostrophe but this is not a solution for a website

You are open for SQL-Injection. Don't concatenate strings to build your query. Instead use SQL-Parameters. That also makes your code more readable and prevents errors like yours.
Here's an example:
int amt;
using (var con = new SqlConnection(ConnectionString)) {
var sql = "INSERT INTO dbo.Message(UserID, Message) VALUES(#UserID, #Message);";
using (var cmd = new SqlCommand(sql, con)) {
cmd.Parameters.AddWithValue("#UserID", userID); // passed as argument
cmd.Parameters.AddWithValue("#Message", txtMessage.Text); // f.e. "John's"
con.Open();
int inserted = cmd.ExecuteNonQuery();
}
}
The same works also with other sql like UPDATE commands.

The problem is that you need to escape Apostrophe by another Apostrophe.
For example have a look at:http://sqlfiddle.com/#!3/d2f75/1
CREATE TABLE tblTEst( col1 NVARCHAR(50))
INSERT INTO tblTest
(Col1)
SELECT 'John''s'

The best solution is to use a prepared statement (or whatever the equivalent in C# is) where your SQL only contains placeholders and you pass the actual values through a different method.
In a character literal, the single quote ' can be used by simply doubling it:
insert into foo (bar)
values
('John''s');

use CHAR(39)between john & s like this: 'john'+CHAR(39)+'s'

Related

How to insert '' (2 apostrophes) into sql

I need to insert '' (2 apostrophes) into a column.
Just the apostrophes without any text.
But I end up inserting \'\' (apostrophes with backslashes)
NpgsqlCommand Cmd = new NpgsqlCommand("INSERT into Table(Col) VALUES(#value), conn);
Cmd.Parameters.AddWithValue("#value", "''");
Cmd.ExecuteNonQuery();
Result: \'\' Appears in my table.
If I use less or more apostrophes it inserts fine but I need exactly 2 and then for some reason backslashes appear.
There seems to be a lot of confusion in the results above.
Npgsql does not perform any escaping in parameters, because they are sent out of band and are not treated in SQL. If your parameter value contains a C# string with two apostrophes, that is what will get inserted into the database.
After running your code above and using psql, I get the following:
var cmd = new NpgsqlCommand("INSERT into foo (name) VALUES (#value)", conn);
cmd.Parameters.AddWithValue("#value", "''");
cmd.ExecuteNonQuery();
npgsql_tests=# select * from foo;
name
------
''
(1 row)
Maybe pgadmin shows values with backslashes - I don't know - but that would be a display issue.
Finally, if you really want to insert a constant value (as opposed to a user-provided one), there's no reason to use parameters. Just embed your value in SQL:
INSERT INTO foo (name) VALUES ('''''');
There are six apostrophes in there: 2 as the string delimiters, and two more escaped apostrophes (in SQL, '' is the escaped form of a single literal apostrophe).
However, if you're reading input from the user, definitely use a parameter.
Try to double up each apostrophe.
Cmd.Parameters.AddWithValue("value", "''''");
Adding an empty text box and using it's text value somehow let's me insert the double apostrophes.
So the answer would be
NpgsqlCommand cmd = new NpgsqlCommand (INSERT into Table (Col) VALUES (#value);
Cmd.Parameters.AddWithValue("#value", textBox1.text);
Cmd.ExecuteNonQuery();
Where texBox1 is just an empty text box.
Probably not the best way of doing this but it works for now.

Set non-Latin alphabet for SQL on C# side

The problem is when user insert non-Latin word to database, if collation not set to that alphabet, the word comes like '?????' But if user insert word like N'word' or I select it like N'word' there is no problem.I use hastable function on C# side so is there any solution for use N'word' format automaticly or must I use N before text everytime I call function?I already use NVARCHAR format by the way.
The simple way to ask;I don't want to use N'word' format every time when I select item from database.Is there any trigger, stored procedure or function for add automaticly N before text I select.
You shouldn't use the N'word' format at all, you should use parameters. When you concatenate values into a string to create a query, it's wide open to SQL injection attacks unless you managage to escape all input exactly right.
Put parameters in the query and add the values to the Parameters collection of the command. Example:
string query = "select Id from Persons where Name = #Name";
using (SqlCommand cmd = new SqlCommand(query, connection)) {
cmd.Parameters.Add('#Name', SqlDbType.NVarChar, 50).value = name;
using (SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
...
}
}
}
Using unicode types like NVarChar for the parameter ensures that the parameter value is sent as unicode, equivalent to the N'word' format.
Why don't you use some sort of ORM. Dapper is a lightweight ORM:
https://github.com/StackExchange/dapper-dot-net
It will solve your problems with parameter passing if this is the troubles you are having

UPDATE string with an apostrophe in the string

I am working on a C# windows form which is connected to MySQL and updates strings within the form. I have everything working properly except for a small issue.
Say you want to update the "notes" field to read "The dog's bone", that apostrophe is causing the SQL query to end and cause an error. How can I get around this please?
UPDATE `database`
SET `notes` = 'The dog's bone'
WHERE `Pet` = 'Dog';
Thanks!
You can escape ' character in MySQL with doubling it like ''.
Other than that, if you use parameterized queries, you will not need this at all. Just pass your The dog's bone string directly to your parameterized query and you will be fine.
Also I strongly suspect you try to use UPDATE instead of SELECT statement. In MySQL, SELECT syntax doesn't have any SET part.
And using a reserved keyword as a column name is a bad idea. As a best practice, change your database column name to non-reserved word.
using(var con = new MySqlConnection(conString))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"UPDATE `database` SET notes = #notes
WHERE Pet = #pet";
cmd.Parameters.AddWithValue("#notes", "The dog's bone");
cmd.Parameters.AddWithValue("#pet", "Dog");
con.Open();
cmd.ExecuteNonQuery();
}
I used AddWithValue method as an example in my code since I didn't know your column types but you don't use it. This method may generate unexpected and surprising results sometimes. Use Add method overloads to specify your parameter type and it's size.
Escape it with another single quote ':
SELECT `database`
SET `notes` = 'The dog''s bone'
WHERE `Pet` = 'Dog';

MySQL asp.net character set doesn't work properly

I use
MySqlConnection con = new MySqlConnection("server=localhost;database=m1cleedb;uid=m1cleeuser;pwd=**;pooling=false");
MySqlCommand cmd = new MySqlCommand("insert into duyurular(adi, kim_icin, duyurulma_tarihi, detay) values(?p_1, ?p_2, ?p_3, ?p_4) ", con);
cmd.Parameters.AddWithValue("?p_1", duyuru_adi.Text);
cmd.Parameters.AddWithValue("?p_2", DropDownList3.SelectedItem.Text.ToString());
cmd.Parameters.AddWithValue("?p_3", duyuru_tarihi.Value.ToString());
cmd.Parameters.AddWithValue("?p_4", duyuru_editor.Value);
con.Open();
code block to insert a row inside my "duyurular" table.
I want to get turkish character support in this but whatever I tried, it didn't work.
I want to be able to put "ğ" char inside of ?p_1. but when I do this, it is inserted like "g".
Then, I decided to try it on my MySQL WorkBench side.
INSERT INTO `m1cleedb`.`duyurular`
(`adi`,
`kim_icin`,
`duyurulma_tarihi`,
`detay`,
`kategori`)
VALUES
('ğğ','ğğ','ğğ','şş','ğğ');
The result is frustrating.. It inserted the "ğ, ş" chars properly...
What could cause the difference between my asp.net insert command and my mysql workbench insert command? ://
I also did put some breakpoints and I saw that ?p_1 paramater's value really goes to "ğğ"..
Any help would be appreciated..
I believe you need to tell the connection what type of encoding you want to use.
MySqlConnection("server=localhost;database=m1cleedb;uid=m1cleeuser;pwd=**;pooling=false");
should be
MySqlConnection("server=localhost;database=m1cleedb;uid=m1cleeuser;pwd=**;pooling=false;CHARSET=utf8;");
C# Mysql UTF8 Encoding

How to change symbol in string using c#

My C# application is able store the data into a SQL Server database. Currently I have to problem when user insert symbol ' in their string/sentences:
Example: I want to 'test' your system
So, when inserting into db the ' symbol will return an error while inserting by using sql query.
My query example :
INSERT INTO TABLE_NAME (POST_BODY)
VALUES ('i want to 'test' your system')
and then my plan here is to change that check the string if contains that ' symbol it will change to " symbol.
I have try using this code, but cannot:
void ChangeSymbol(String str)
{
Console.WriteLine("\"{0}\"", str);
Console.WriteLine("\"{0}\"", str.Replace(''', '"'));
}
Please anybody help to give some idea to face this problem. Thanks in advance.
There is no problem inserting a single quote into a database using SQL code. If you want to insert a text literal then you simply escape the single quote with another single quote, e.g.
INSERT INTO MyTable (GivenName, FamilyName) VALUES ('James', 'O''Connell')
If you're inserting a separate value into a SQL statement then you should be using parameters no matter the data type, so an issue with single quotes never arises, e.g.
mySqlCommand.CommandText = "INSERT INTO MyTable (GivenName, FamilyName) VALUES (#GivenName, #FamilyName)";
mySqlCommand.Parameters.AddWithValue("#GivenName", givenName);
mySqlCommand.Parameters.AddWithValue("#FamilyName", familyName);
Use parameter binding. I don't have a sample code to put in since we dont use MSSQL
here's a sample
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx
You escape single quotes by doubling them. So try this:
string example = "I want to ''test'' your system";

Categories

Resources