Length of string in String.Format() - c#

It's may be I'm doing something wrong but don't know why I'm getting such issue.
I'm using string.Format which took around 130 parameters my code look like as below
string query = string.Format(#"Insert into TB_LN_CASES (
col1,
col2,
col3,
col4,
...
...
col129,
col130) Values ({0},{1},{2},{3}.....{129})",
col1.ToString(),
col2.ToString(),
col3.ToString(),
col4.ToString(),
...
...
col130.ToString());
The output which I'm getting in string is like
Insert into TB_LN_CASES (col1, col2,col3,col4,
...
...col129,col130) Values (abc,efd,gr,y,t,ui,u,re,re
String is incomplete, don't know what is the reason behind this or is there any alternative to do this, please suggest
Is there any max length constraint for string.Format ?

That is so totally not a string.format issue that it is not funny.
Please consider doing a little basic debugging yourself.
Values (abc,efd,gr,y,t,ui,u,re,re
This is not valid SQL. See, string values have to be in paranthesis of some sort ('abc' instad of abc).
Simply speaking your (btw, the old string.format syntax is hard to read - learn to use $"" strings, the new syntax for formatting in .NET 6.0) generated SQL is bad and you never considered this a SQL error.
Now, for the length issue - that is no, there is no sensible limit that you would reach. There is one, but it is LONG (not sure about the string limit - 2 gigabytes RAM?). It is likely you have a serious presentation issue (as in: The string is there, you just do not see it, like in the debugger, which may limit the output length).
I would reformat that to use he new $"{paramname}" syntax - it is a LOT easier to debug once you hit 10 or 20 parameters.
Please also note: The ToString calls on all those parameters are surplus (default call anyway).

If you are building up a SQL query, I would strongly recommend you use parameters in your query.
Here is an example:
string strQuery = "Insert into TB_LN_CASES (col1, ...) VALUES (#columnOneVariable, ...)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#columnOneVariable", "yourValue");
At the moment you are very vulnerable to SQL injection.
To answer your question about the limit on String.Format(), please read here

try this:
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = #"Insert into TB_LN_CASES (col1, col2,col3, ..)
Values (#value1, #value2, #value3, ..) ";
cmd.Parameters.Add(new SqlParameter("#value1", value1));
cmd.Parameters.Add(new SqlParameter("#value2", value2));
cmd.Parameters.Add(new SqlParameter("#value3", value3));
cmd.ExecuteNonQuery();
}

string.Format("#"Insert into TB_LN_CASES{0},{1},{2}", col0,col1);

Related

Can this be victim of sql injection

Hi I am getting id value from a drop down list and passing it to a code behind method which passes value to sql to do some operation.
I was wondering if it is the right way of doing it.
if it is not then why not and how someone can inject it with sql injection and what would be the solution.
protected void Drop1_SelectedIndexChanged(object sender, EventArgs e)
{
int abcID;
abcID= Convert.ToInt32(drop1.SelectedItem.Value);
string sc = "SELECT dddd FROM table1 WHERE abcID NOT IN("
+ abcID + ")";
using (SqlDataSource ds = new SqlDataSource(ConnectionString(), sc ))
{
}
Since you are using, Convert.ToInt32 on the value sent by the user, SQL injection would not occur. Invalid values would throw exceptions.
However it is a generally a good practice to use Parametrized queries.
That way even string values would be safe.
SqlCommand command = new SqlCommand("SELECT dddd FROM table1 WHERE abcID NOT IN(#myID)");
command.Parameters.AddWithValue("#myID", abcID);
You should use parametrized queries as follows:
string sc = "SELECT dddd FROM table1 WHERE abcID NOT IN(#par)";
cmd=new SqlCommand(sc,conn);
cmd.Parameters.AddWithValue("#par",abcID );
da=newsqldataadapter(cmd);
ds=new DataSet();
da.Fill(ds);
cmd.excutenonquery();
Go through Following:
http://en.wikipedia.org/wiki/SQL_injection
No, this particular example cannot be used for SQL injection.
However, if you train yourself to always use stored procedures or parametrized queries, you will never get it into your system to create SQL statements like this. This way, you will never make something (possible by accident) that would create SQL injection attack vectors.
For best practice you should use parameterized queries instead.
SqlCommand command = new SqlCommand("SELECT dddd FROM table1 WHERE abcID NOT IN( #Value )"
command.Parameters.Add(new SqlParameter("Value", abcId));
You could assume that you are safe due to the fact that Convert.ToInt32 will throw a FormatException if someone was to attempt to inject something like DROP TABLE table1; into your drop down list and pass it back to the server. However, I would strongly recommend the use of paramertized queries.
Since you converted the value to a 32bit integer, you won't be having "injection" problems. There are better ways to escape values though. (see parameterization)
Not a nice way to do things, but it would survive sql injection... so, no... u won't have that problem

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'

Why we passing values using parameters?

option 1: in this values are inserted using parameters
string insertstr = "INSERT INTO table_name(eid, eName, Dept) " +
"VALUES(#eid, #eName, #dept)";
SqlCommand cmd = new SqlCommand(insertstr, con);
cmd.Parameters.Add("#eid", SqlDbType.Int).Value = Convert.ToInt32(textBox1.Text);
cmd.Parameters.Add("#ename", SqlDbType.VarChar, 50).Value = textBox2.Text.ToString();
cmd.Parameters.Add("#dept", SqlDbType.VarChar, 100).Value = textBox3.Text.ToString();
Option 2:
SqlCommand cmd = new SqlCommand("INSERT INTO table_name(eid,eName,Dept) values('"+ textBox1.Text +"','"+ textBox2.Text +"','"+ Textbox3.Text +"'", con);
cmd.ExecuteNonQuery();
Most of the projects i had seen the 1st option... what is the use of passing values using parameters?? any advantages by passing values using parameters?? your suggestion plz..
You don't have to care about quoting special characters. If you forget to quote a SQL-Injection attack is possible.
If you use Option 2 and one enters the following into Textbox3
'); DELETE * FROM table_name; --
the following SQL statements are excecuted:
INSERT INTO table_name(eid,eName,Dept) values ('value1','value2','');
DELETE * FROM table_name; -- ')
The second statement deletes every row from table_name. Instead of a delete statement any possible statement could be inserted there.
Several reasons:
You don't have to worry to escape special characters (like ') to avoid SQL errors or SQL injections (as explained by H-Man2).
You don't have to worry to transform C# types to SQL types. For instance:
If your NumberDecimalSeparator is equal to the comma , and you want to insert a Double value in your database, you normally have to replace the comma by a point. No need to worry about that with parameters.
No need to worry about DateTime formats neither.
...
I find also the code more readable and easier to maintain with parameters when your SQL queries start to have a great length.
You should NEVER use option 2.
This is very bad practise, and very open to SQL Injection.
Always stick with Option 1. This is the best option by far.
Read here for more information on SQL Injection:
http://en.wikipedia.org/wiki/SQL_injection

A simple SQL problem: Making an SQL insert statement with text string that contain ' characters

I follow the syntax of
INSERT INTO Table1
VALUES (value1, value2, value3…)
This has worked fine so far. But now I have some values that contain normal English text like "I'm going home". The ' character ruins the SQL command in C#. I have written the following:
command.CommandText = "INSERT INTO Bio VALUES ('" + name + "','"I'm going home" + "');
evaluates to
INSERT INTO Bio VALUES ('Peter','I'm going home')
which obviously will not work. How do I make sure special character will not ruin the SQL statements?
Use SqlParameter for heaven's sake. Otherwise your program will be vulnerable to SQL Injection. It will also solve your problem with the special characters.
Learn about parameterized queries for your provider. They exists for Odbc, OleDb, Sql, etc.
command.CommandText = "INSERT INTO Bio Values (#name, #text)";
command.Parameters.Add(/* appropriate param type for your provider */); // add for #name, #text, etc.
// execute query
Use two single quotes whenever there is a single quote you want to escape
Also instead of building your queries like this, you should use parameterized queries in a language of your choice. Escaping the characters yourself opens the door for SQL Injections.
Usually you can escape a single quote by screening with another one.
For example the following is a valid statement
INSERT INTO myTable (Column1) VALUES ('Hello I''m Jack');
However I suggest you using parameters.
command.CommandText = "INSERT INTO Bio VALUES (#Name, #OtherValue)";
command.Parameters.AddWithValue("Name", name);
command.Parameters.AddWithValue("OtherValue", "I'm going home");
One addition point in favor of using parameters is that you are free from burden of formatting and other stuff. I mean date values, uniqueidentifiers, etc.
I do use
HttpUtility.HtmlEncode(text)
It makes all that SQL injection stuff disappear, and it seems easier than to use parameters.
Don't forget to use
HttpUtility.HtmlDecode(text)
to get your input back in the form you received it

Categories

Resources