C# Textarea value with newline save in SQL Server - c#

I have an insert statement that takes the raw text from text area and stores it. We only allow editing the same value and not display them.
During the insert the newline along with slash [abc\\ndef] is removed for some reason by SQL Server. So what is the C# solution to this?
Insert Statement
INSERT INTO Comments (Comment) VALUES (#clientValue)
where comment is the column name and #clientValue contains the string abc\\ndef when viewed in the Visual Studio debugger
Demonstration
SELECT 'abc\
def' AS ColumnResult;
C# Command Snippet
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Comments(Comment) VALUES (#clientValue)"
cmd.Connection = conn;
SqlParameter param = new SqlParameter();
param.ParameterName = "#clientValue";
param.Value = txtComment.Text;
cmd.Parameters.Add(param);
conn.open();
execute the statement here
running above statement the \ and \n newline from the textarea are getting removed. How do I avoid this?

What is the column type for the storage column? If it is varchar or text then change it to nvarchar/ntext.
If any of that doesn’t work you can simply replace /n with something like or use html but it would require that you update the string before storing it in database and before adding it back to textarea. This is far from ideal solution but it would work.

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.

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

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

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'

How to insert string containing single or double quotes

If I want to insert a statement which contains quotation mark, how is it possible ?
For Example I have a text box and I enter:
Future Swami Vivekananda’s grand father's name was "____" .
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');
Use a parameterized query - then quotes don't matter at all. Also - your database doesn't get taken over by SQL injection - so win/win really.
You can double up the quote:
INSERT INTO table
VALUES ('Future Swami Vivekananda''s grand father''s name was "____"')

Getting error while store data in sql server 2005 through textbox

I am storing data (approx. 1500 words) in SQL server 2005 through textbox and button. I am using this code.
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
String query = String.Format("insert into try (data,sno) values ('{0}',22)",TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
Label1.Text = "submitted";
conn.Close();
}
I have column 'data' of data type 'char(4000)'.
Problem is that, when I store 1st paragraph (approx 1500 words), it stored successfully. But when I stored another paragraph (approx 1500 words), it show me the error.
"Incorrect syntax near 's'. Unclosed quotation mark after the
character string ',22)'."
What is the problem ??
Use Parameters
String query = "insert into try (data,sno) values (#data,22)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#data", TextBox1.text);
cmd.ExecuteNonQuery();
In this way you don't need to worry about the presence of single quotes in your text and, the most important thing, you avoid SqlInjection Attacks
String.Format will not escape the input string suitably for use in an SQL statement, which will lead to errors & serious vulnerabilities.
You should use Parameterized Queries which are designed specifically to address this.
This sounds like you have an ', or multiple 's, in the TextBox1.Text. You will need to replace all single quotes for double.
String query = String.Format("insert into try (data,sno) values ('{0}',22)",Replace(TextBox1.Text,"'","''"));
However, this approach will open you up to SQL Injection attacks. I'd recommend using a Stored Procedure, like the following:
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spInsertDataIntoTry";
cmd.Parameters.AddWithValue("#data", TextBox.Text);
cmd.ExecuteNonQuery();
Otherwise, you could use Parameters like others have mentioned.
Does your text contains ' letter? If yes then it is breaking INSERT query.
If you would try to insert following text:
Hello' there
Then your query would look like this:
insert into try (data,sno) values ('Hello' there,22)
Which results in incorrect query.
This is not the way queries should be done, because it leads to security issues (read more: SQL Injection) you should use parametrized queries.
"Incorrect syntax near 's' - this indicates your sql statements is wrong.
i guess that your input content maybe contains sql server keywords, so check your 2nd paragraph is there any keyword such as "'".
for example:
2nd paragraph is: how's the weather? it's cool!!!!!!!
so the sql statement is: insert into try (data,sno) values ('how's the weather? it's cool!!!!!!!',22)
it will arise an exception incorrect syntax near 's'

Categories

Resources