Random special characters in insert - c#

I have the following Code in C# ( Sql server (LocalDB)\v11.0)
If Definition property has no special character , the Insert executed. but
some times it has an unknown special character in it , and i recive the Error.
for()
{
if(){
DB.Docommand("INSERT INTO Test5(P_Def) VALUES('"+ pro.Definition + "')");
}
}
in database the data type is nvarchar(Max)
but i receive the following error:
incorrect syntax near .....
I want to insert my property with special characters.
What can id do?
Thanks

Parameterize your insert. In addition to gaining an ability to insert strings with any characters that are valid inside nvarchar, you will also fix a major security problem by avoiding a potential sql injection attack:
var cmd = new SqlCommand("INSERT INTO Test5(P_Def) VALUES(#Def)", con);
cmd.Parameters.AddWithValue("#Def", pro.Definition);

Related

Create Database Dynamically Using C#

I am trying to create a database using this code:
var createDatabaseQuery = "exec ('CREATE DATABASE ' + #db)";
var sqlCommand = new SqlCommand(createDatabaseQuery, sqlConnection);
sqlCommand.Parameters.Add("#db", SqlDbType.Text);
sqlCommand.Parameters["#db"].Value = "DbName";
sqlCommand.ExecuteNonQuery();
The above works perfectly but I try to do concatenation as follows, it throws an exception:
var sqlCommand = new SqlCommand(createDatabaseQuery, sqlConnection);
sqlCommand.Parameters.Add("#db", SqlDbType.Text);
sqlCommand.Parameters["#db"].Value = "DbName" + CustomId; //Doing the concatenation here
Exception:
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '-'
I know, there could be better ways to do it. But is there any way that I can make the above work?
Time to learn the real intricate sides of SQL.
The way you wan t to write it - is incorrect in multiple ways. DEBUG THE SQL. Do not care about the C# code, look at the SQL...
In your case - naming conversions.
Tables, databases etc. can not contains a "-" - OR they must be marked.
CREATE DATABASE my-database -> Error
CREATE DATABASE [my-database] -> correct, the [] brackets names and thus... no processing of the "-" is tried.
This is quite clear in the SQL documentation, but a part many people overlook (mostly because in most cases it does not matter). They likely wonder why generators bracket every item name (Database, schema, table, COLUMN). Well, that is the reason. What do you think "-1" means? Minus one, processing, or part of a name - the server has no way to determine this. Help him.
You need to make sure you are quoting the name correctly using QUOTENAME, because it contains characters that need escaping.
var createDatabaseQuery = "exec ('CREATE DATABASE ' + QUOTENAME(#db))";
Also, the parameter type should be nvarchar(128)
sqlCommand.Parameters.Add("#db", SqlDbType.NVarChar, 128).Value = "DbName" + CustomId;

SQLInjection with Npgsql/Postgres

I want to learn how SQLInjection is working with the PostgresqlDb. I am using the Npgsql in C#.
So this is my Query, which is called, when I rename a folder:
cmd.CommandText = "UPDATE allfolder.folder SET folder_name = '" + foldernamenew + "'";
cmd.ExecuteNonQuery();
I now tried to pass the following value into the textfield:
abcdef; INSERT INTO allfolder.folder (id, folder_name) VALUES (56,"aaaaaaa");
Then AJAX is fired.
The output I assumed is, that all folders in the table has the folder_name "abcdef" and that I have a new folder with the id "56" called "aaaaaa". This is not the case, because the semicolon is not recognized as delimiter and so the name of each folder_name are "abcdef; INSERT INTO ....". I do not want to change it on DB side that multiqueries are allowed.
So my questions are:
How do I need to prepare the SQL statement, that I achieve a Injection?
Is an injection even possible, when you are not allowed to execute a second qry because the semicolon isn't recognized?
I am only talking about Npgsql and postgres.
As Laurenz mentioned above, this should work:
abcdef'; INSERT INTO allfolder.folder (id, folder_name) VALUES (56,'aaaaaaa'); -- test
Make sure, that you don't mix single and double quotes. A common mistake in SQL. You need the single quote before the semicolon, otherwise it is in the textstring, because you have no delimiter.
“Multiqueries” (several queries in one line, separated by semicolon) are always allowed in PostgreSQL.
Your problem are the multiple errors in your SQL:
Missing single quote after abcdef.
Double quotes instead of single quotes around aaaaaaa.
No single quote or line comment at the end of the statement.
Speaking pointedly: you have to learn SQL before you can learn SQL injection.

Error: String or binary data would be truncated. The statement has been terminated. aspx

i want to insert data into my tbl_Transaction_Master table.
here is my database table tbl_Transaction_Master
and my query for database insert command is
SqlCommand cmd2 = new SqlCommand("insert into tbl_Transaction_Master(Supplier_ID,Order_Price,Unique_ID,Supplier_Name,He_Is_a,Transaction_Date) values ('" + WebUserID + "','" + Session["Order_Price"] + "','" + Session["WebUserid"] + "','"+User+"','WebCustomer',getdate()); SELECT SCOPE_IDENTITY()", conn);
int temp = cmd2.ExecuteNonQuery();
Session["order_ID"] = temp;
i am getting the error as mentioned above.
There are many problems in your code, not just the one that raises the current exception.
First: You have text fields with a precise size, you cannot insert more characters than the size of the field. We don't know anything about the value passed for the SupplierName but the string WebCustomer is 11 chars and you try to insert it in a field with space only for 10 chars.
Second: Using nchar means that your fields are always filled with spaces to reach the length required. Of course this is inefficient with a lot of records, not to mention the work required to trim away those spaces when you need to show your data.
Third: ExecuteNonQuery returns the number of rows affected by your command. In this case it is always 1, you don't get the return value of SELECT SCOPE_IDENTITY(). Use ExecuteScalar.
Fourth: Some of your fields are numeric, you insert strings for them. This means that the database engine try to convert them back to the correct datatype. Usually, for integers, you can go away freely, but with floats there is a higher chance that you get a datatype mismatch error caused by difference between the locale settings of your code and the locale settings of your database. Fix for that in the next point.
Fifth: You should use parameters not string concatenation. This avoids the Sql Injection hack or the parsing error caused by automatic conversion of a string back to a numeric value. A mismatch from the locale settings used in your code and the database setting will cause errors. With a parameter you specify the type and do not convert the value. The database engine is happy.
So.....(after changing to nvarchar and after checking the length of the values)
string cmdText = #"insert into tbl_Transaction_Master
(Supplier_ID,Order_Price,Unique_ID,
Supplier_Name,He_Is_a,Transaction_Date) values
(#webid, #price,#sessionid,#user,'WebCust.',getdate());
SELECT SCOPE_IDENTITY()";
SqlCommand cmd2 = new SqlCommand(cmdText, conn);
cmd2.Parameters.Add("#webid", SqlDbType.Int).Value = WebUserID
cmd2.Parameters.Add("#price", SqlDbType.Decimal).Value = Session["Order_Price"];
cmd2.Parameters.Add("#sessionid", SqlDbType.Int).Value = Session["WebUserid"];
cmd2.Parameters.Add("#user", SqlDbType.NVarChar).Value =User;
int temp = Convert.ToInt32(cmd2.ExecuteScalar());
Session["order_ID"] = temp;
You are inserting a value in a table column which exceeds column length. That's why the error is there. Check length of each of the values you are inserting into table against respective column lengths.
You are probably inserting a text longer than the designated size. For instance, for Supplier_Name, you are designating an nchar of 20. If you are trying to insert a value larger than 20 characters. You will get this error.
Try changing the size of the data type to fix this.
Two things.
One: The error is occurring because you trying to place data into the field which is larger than allowed so for nchar(20) it will accept an input of 20 or less and pad it up to 20 charters (Varchar will carry the came cap but not pad the data and save space).
Two: It is safer and advised as a best practice to use parameters when inserting values into the database.
You are inserting more characters but you define less.
for example:
column datatype is varchar(5) but you are inserting 6 characters.

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'

C# ODBC Exception Incorrect String value

I am using C# to parse a chat log and insert messages into a database.
When trying to insert the string "Don't worry, it's unloaded"
(with the double quotes) it gives me the following exception:
System.Data.Odbc.OdbcException: ERROR [HY000] [MySQL][ODBC 5.1 Driver][mysqld-5.5.11]Incorrect string value: '\xEF\xBB\xBF it...' for column 'msg' at row 1
at void System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)
The database is using latin-1 default collation for the encoding scheme.
I have tried switching to utf-8 but this gave me the error on the same line.
Not sure what it means to your specific error, but EF BB BF is the UTF BOM character which could be causing an issue.
This answer pointed out that the client connection needs to be set to the proper character set as well. It could be that the C# client character isn't matching the MySQL encoding.
Depending on your chosen way to insert data (I assume by building the SQL directly), the ' character needs to be escaped. That's because ' is string delimiting character in most databases.
What you need to insert is "Don''t worry, it''s unloaded", with the single quotes escaped by doubling them.
!Important: You need to be careful about raw using raw SQL as it can easily create security holes that can SQL injection. Use parametrized queries whenever possible or fully escape the query sent to the server.
Don't forget that if you're constructing the SQL statement (don't! -- use a parameterized query instead), if the construct winds up looking like:
insert foo ( bar ) values( "This is my data" )
The insert will fail because the double quote introduces a quoted column name. It is not the same as a string literal which is quoted with the apostrophe (').
User SQL Parameters instead of using raw sql. There can be SQL Injection security issue and these sort of issues.
See how to use sql parameters mysql-c#
Eg:
MySqlCommand mySqlCommand1;
...
mySqlCommand1.CommandText = "INSERT INTO dept (deptno, dname, desc) VALUES (?, ?, ?)";
mySqlCommand1.Parameters.Add("param1", 30);
mySqlCommand1.Parameters.Add("param2", "SALES");
mySqlCommand1.Parameters.Add("param3", #"Don''t worry, it''s unloaded");

Categories

Resources