How to add one double-quotes (") to string? - c#

I writing a request in C# for MySql Database and I need to write in string of the command double-quotes.
Something like:
String command ="Insert into table (column) values ("" + textBox1.Text + "")";
But I have a syntax error of C#. When I try chenge " to `
String command ="Insert into table (column) values ('" + textBox1.Text + "')";
I have a syntax error of Mysql(1054). Row column has a type varchar. How to correctly write this request in a program?

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

Related

MySQL Query Returns Parameter Column Name [duplicate]

This question already has answers here:
How to pass a table as parameter to MySqlCommand?
(2 answers)
Closed 6 years ago.
I am working in C# and MySQl in VS2015 to query my database and return a the information in a VARCHAR type column titled "method". However, the query returns the string "method", and not the values of the method column.
below is the code:
string queryOne = "SELECT " + "#columnName" + " FROM log.transactions";
MySqlCommand cmdOne = new MySqlCommand(queryOne, connectionString);
cmdOne.Parameters.AddWithValue("#columnName", "method");
MySqlDataReader dataReaderOne = cmdOne.ExecuteReader();
while (dataReaderOne.Read())
{
Console.WriteLine(dataReaderOne.GetString(0));
}
dataReaderOne.Close();
While this is the output:
method
method
method
.
.
.
.. for the number of rows in the method column. Is this a formatting problem? Is it possible that the configuration of my database is preventing VarChar's from returning correctly? When I change the query to query a column of type INT, it returns the correct values for an INT type column.
You can't parameterize a column name in a select statment. What you're doing is exaclty like saying select 'foo' from log.transactions. It selects the string 'foo' once for each row. You're just sticking a string value in there; it's not parsing the string value as SQL.
What you can do (if you can afford it) is select * from log.transactions, then your C# code can grab the data in whatever column the caller passed you the name of. With a lot of rows you could be dragging a lot of useless junk back from the DB though.
What you want in the code you show, though is just this:
string queryOne = "SELECT method FROM log.transactions";
If you really want to parameterize "method", that's sketchy because of SQL injection vulnerabilities.
string queryOne = "SELECT " + fieldname + " FROM log.transactions";
That looks good until some comedian using your application gives you a value of "0; drop table log.transactions;--" in the textbox. Then you've got troubles. If you ever concatenate a string variable into a SQL string that you're going to execute, you've got to be fanatical about sanitizing it, and even then you want to avoid it any way you can. It's Russian roulette.
Your query formation has to be like if you want to keep your column dynamic.Now pass column name accordingly.
string queryOne = "SELECT " + column_name + " FROM log.transactions";
MySqlCommand cmdOne = new MySqlCommand(queryOne, connectionString);
MySqlDataReader dataReaderOne = cmdOne.ExecuteReader();
while (dataReaderOne.Read())
{
Console.WriteLine(dataReaderOne[column_name]);
}
dataReaderOne.Close();

C# String literal with concatenation

I have a ASP.NET C# application, and I frequently use the verbatim string literal such as
dbCommand.CommandText = #"INSERT INTO MYTABLE (COLUMN, COLUMN2)
VALUES ('data', 'data)";
This is all great, but when I try to concatenate the string with a variable such as
dbCommand.CommandText = #"INSERT INTO MYTABLE" + Session["table_extension"] + "(COLUMN, COLUMN2)
VALUES('data','data')";
I get an error stating Newline in constant. How can I avoid this while still using the # string literal?
Put the # in front of the second string literal or use String.Format()
1) Don't concatenate strings to build SQL commands, it's really dangerous and error phrone (see SQL Injection: http://www.w3schools.com/sql/sql_injection.asp).
You should use ADO.NET parameters (http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06)
2) If you are going to concatenate strings, use string.Format like:
var sql = string.Format("INSERT INTO MyTable ('col1') VALUES ({0})", col1Value);
Or use the new simplified syntax which has a better compile time check:
var sql = $"INSERT INTO MyTable (col1) VALUES ('{col1Value}')";
This will work for you!
dbCommand.CommandText = #"INSERT INTO MYTABLE" + Session["table_extension"].ToString() + "(COLUMN, COLUMN2)
VALUES('data','data')";

Use of commercial #AT when dealing with data access in ASP.Net?

Two small issues, mostly concerning the #AT syntax when dealing with data in ASP.Net (C#). Most online tutorials show a lot of this following type of code but fail to mention (or I may have overlooked) the actual purpose of the ampersand although they do explain the general purpose of the code. In this example, just querying the database to get data pertaining to a certain month for a calender control.
protected DataSet GetCurrentMonthData(DateTime firstDate,
DateTime lastDate)
{
DataSet dsMonth = new DataSet();
ConnectionStringSettings cs;
cs = ConfigurationManager.ConnectionStrings["ConnectionString1"];
String connString = cs.ConnectionString;
SqlConnection dbConnection = new SqlConnection(connString);
String query;
query = "SELECT HolidayDate FROM Holidays " + _
" WHERE HolidayDate >= #firstDate AND HolidayDate < #lastDate";
SqlCommand dbCommand = new SqlCommand(query, dbConnection);
dbCommand.Parameters.Add(new SqlParameter("#firstDate",
firstDate));
dbCommand.Parameters.Add(new SqlParameter("#lastDate", lastDate));
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(dbCommand);
try
{
sqlDataAdapter.Fill(dsMonth);
}
catch {}
return dsMonth;
}
First issue: What do #firstDate and #lastDate mean or reference in the database string query? Is that referencing the parameters being passed in GetCurrentMonthData method or the actual column name in the database table ?
query = "SELECT HolidayDate FROM Holidays " + _
" WHERE HolidayDate >= #firstDate AND HolidayDate < #lastDate";
Second issue: What is the difference between #firstDate and firstDate? Am I correct in saying firstDate is the actual parameter variable itself?
dbCommand.Parameters.Add(new SqlParameter("#firstDate",
firstDate));
I agree with #har07. That is not a ampersand. An ampersand, as far as I know, looks like this -> &. To answer the question, the 'at' sign (#) is used to indicate variables in a parameterized query in c#.
In the code
dbCommand.Parameters.Add(new SqlParameter("#firstDate",firstDate));
you are assigning the value of the DateTime variable firstDate to the #firstDate variable in your query.
Here's an example that's a bit less confusing(I hope):
Let's say I have a string variable called myName and I want to pass that to my query select * from students where name = #name.
To pass the value of myName to #name in my query, I would do
dbCommand.Parameters.Add(new SqlParameter("#name",myName));
I hope that helps.
Your First Question :
According to the documentation, the name must start with an #:
The ParameterName is specified in the form #paramname.
More Information :
Is it necessary to add a # in front of an SqlParameter name?
Second Question :
First, that isn't ampersand but at sign or commercial at. It is used in this particular context to indicates an SQL parameter name.
And this part showing how you pass the actual value (contained in the firstDate C# variable) to the SQL parameter (#firstDate) :
dbCommand.Parameters.Add(new SqlParameter("#firstDate",
firstDate));
You can read your parameterized SQL query statement like string concatenation but with big advantages (the former save you from SQL injection, arbitrary data type to string conversion with correct formatting*, etc) :
query = "SELECT HolidayDate FROM Holidays " + _
" WHERE HolidayDate >= " + firstDate + " AND HolidayDate < " + lastDate;
*) See that in the string concatenation version above you need to convert firstDate and lastDate to string with correct format according to your RDBMS local settings to make it work.
The main use of #inputvalue in query statement is to avoid sql injection attacks.
If you use normal concatenation method in building query statement, Hackers can easily bypass the statements with sql injection.
Eg:
"Select * from user where username ='" + username.text + "' and password ='" + password.text + "'"
If you use the above statement to validate the user login, think what will happen if the user types a' = 'a') or 'sometext in username textbox and sometext in password box. It will returns more than one record on execution and enters into account area, if you checks with no of return records in user validation.
To avoid this, Microsoft introduced #parameter to build sql query statements. Whatever value you pass in the #parameter is considered as input parameter value and you can't inject sql statements in it.
Answer for your second question
dbCommand.Parameters.Add(new SqlParameter("#firstDate",
firstDate));
The above method is used to replace the #parameter(first argument in Add method) with parameter value(second argument in Add method). It uses # as the delimiter. it checks if there is a word with prefix '#' in query statement, it will be marked as a parameter and it is replaced by the actual value which is passed as the second argument in the Add method.

As it does not seem possible to specify the name of a table in a parameterized query, is there a safe alternative?

I have a class, ValuesField, which manages values for ComboBoxes.
The constructor specifies a database table from which the values can be retrieved, along with two fields from which to SELECT data.
public ValuesField(string databaseTable, string idField, string valueField)
{
this.databaseTable = databaseTable;
this.idField = idField;
this.valueField = valueField;
}
My method, GetValues() retrieves this data (from which a ComboBox can then be populated). I was constructing the CommandText as a simple string, however I wanted to use a parameterized query for safety.
The simple string command -
dbCommand.CommandText = "SELECT " + idField + "," + valueField + " FROM " +
databaseTable + " ORDER BY " + valueField;
The parameterized query -
dbCommand.CommandText = "SELECT #idField, #valueField FROM #databaseTable
ORDER BY #valueField";
dbCommand.Parameters.AddWithValue("#idField", idField);
dbCommand.Parameters.AddWithValue("#valueField", valueField);
dbCommand.Parameters.AddWithValue("#databaseTable", databaseTable);
dbReader = dbCommand.ExecuteReader();
The parameterized query throws a MySqlException on ExecuteReader() with the Message 'You have an error in your SQL syntax'.
I checked the value of the CommandText at the point the Exception is thrown and it (using the Watch) and the CommandText still shows as "SELECT #idField, #valueField FROM #databaseTable ORDER BY #valueField" - so I am not sure how to examine the syntax for any obvious errors as I would normally do.
I see that this is apparently not possible according to this answer.
Is there a way to view the actual CommandText with the values included in order to diagnose syntax errors?
Is there a safe alternative to specify a table name, if indeed using a parameterized query is not possible?
Try creating a generic table for your combo boxes: [id, value, combo] and a add the combo metadata to other tables.
Or just use a repository pattern :)

Problems with saving data with single quote ' in the query [duplicate]

This question already has answers here:
Single and double quotes in Sql Server 2005 insert query
(3 answers)
Closed 8 years ago.
I have an asp.net project in which I am getting an error while saving data.I have a text box for school name, most school names get saved but if I have a school name like St.Xavier's, it creates a problem during the execution of the insert query.This happens due to the presence of a single quote in the text.As a result the eventual query that I get is:
Insert Into tblSchool(SchoolName, CreatedBy, CreatedOn)
values('St.Xavier's',1,'2014-6-13 13:14:16')
How can I save data with single quotes in the text? I am using Microsoft SQL Server 2005.
You haven't shown your code, but I strongly suspect that you've got code such as:
// Bad code!
String sql = "Insert Into tblSchool(SchoolName, CreatedBy, CreatedOn) "
+ "values('" + name + "'," + creator + ",'" + date +"')";
Don't do that. It's hard to read, error-prone in terms of conversions, and vulnerable to SQL Injection attacks.
Instead, you should use parameterized SQL. Something like:
String sql = "Insert Into tblSchool(SchoolName, CreatedBy, CreatedOn) "
+ "values(#Name, #CreatedBy, #CreatedOn)";
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = name;
command.Parameters.Add("#CreatedBy", SqlDbType.Int).Value = creator;
command.Parameters.Add("#CreatedOn", SqlDbType.DateTime).Value = date;
int results = command.ExecuteNonQuery();
...
}
See the SqlCommand.Parameters documentation for more details.
You need to work with bind parameters in your SqlCommand. Anything else is bound to fail.
You need to quote the ' with another '. I.e.:
values('St.Xavier''s',1,'2014-6-13 13:14:16')

Categories

Resources