When I am sending decimal value from C# for example : 5.54
When I am executing query I can see that my variables are represented as 5,54
Anyone have an idea how to achieve to get DOT and not COMMA?
Here is my code:
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
OSGconv.deciLat, OSGconv.deciLon);
conn.Open();
cmd.ExecuteNonQuery();
}
Anyone have an idea how to achieve to get DOT and not COMMA?
Don't embed the values into your SQL directly to start with. Use parameterized SQL instead. See the documentation for MySqlCommand.Parameters for an example. You should always use parameterized queries:
They separate code from data
They prevent SQL injection attacks (not an issue for these numbers, but consider strings...)
They prevent conversion issues like this
There's a more general point here: don't perform any more conversions than you have to. Every time you convert data from one form to another, you risk losing data or worse. If you can keep your data in the most appropriate representation for as long as possible, you'll minimize the problems.
I totally agree with the other advice. As to the other question regarding comma or dot, it depends on the CurrentCulture. To get the right format you would have to use a ToString, providing Culture.InvariantCulture as the second parameter. This will use the dot for decimal separator.
But, I insist, the other answer is very good advice: use DbParameters. And I add: pass the value as held in C#, not converting it to string. It will be correctly handled by the ADO.NET provider. I.e. if you have to pass a float variable, do pass it without converting to string, but as is, as a float value.
Related
I'm trying to follow this video that teaches how to inserting data to database with Visual Studio C#. The place I'm stuck on is the syntax in the string Query (you'll know what I'm mean when seeing the video). The code can be seen at the 5:36 mark. I'm confused by the single, double quotes and the + sign in the portions after values (.... Are + signs required in the parameter, or they are used to concatenate. Please help this novice who is trying to learn the language of C#. Much appreciated.
Edit:
string Query="insert into database.edata (Eid,name,surname,age) values('"+this.Eid_txt.Te...
Ok. The insert statement is this (a bit simplified since I cannot see the rest in the video):
"insert into database.edata (Eid) values ('"+this.Eid_txt.Text + '")";
The + sign is used for concatenation of the strings. The single quotes are required as a part of T-SQL to quote the strings. The double quote is to end the C# string and concatinate it and the value of the text box.
That being said, this is an outdated method of doing this. You should be using Sql parameters instead of concatinating strings this way.
So I am reading a book on ADO, and I have reached the end of the chapter describing parameters and queries in ADO. In the book it provides the following code examples to pass a parameter to SQL server:
Dim paramValue As New SqlParameter("#NewSalary", SqlDbType.Money)
paramValue.Value = 50000#
salaryUpdate.Parameters.Add(paramValue)
paramValue = New SqlParameter("#EmployeeID", SqlDbType.BigInt)
paramValue.Value = 25&
salaryUpdate.Parameters.Add(paramValue)
salaryUpdate.Parameters.AddWithValue("#NewSalary", 50000#)
salaryUpdate.Parameters.AddWithValue("#EmployeeID", 25&)
For C# it shows
salaryUpdate.Parameters.AddWithValue("#NewSalary", 50000m);
salaryUpdate.Parameters.AddWithValue("#EmployeeID", 25L);
What the book doesnt really go into is why the values being defined have and M,L,#,& characters appended to them. Why is this? And the difference between vb and c# is perhaps just syntax?
Tried doing some research on MSDN, but these types of examples dont appear there, or so it seems.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Thanks for any clarification
In VB.NET and C# you could add a postfix character to a constant value to explain its datatype. It is a leftover from the VB6 days to help with portability issues. Nowadays you should try to use an explicit constant Const NAME As Type = value declaration and use the suffix only when needed.
See VB.NET Type Characters on MSDN
For the AddWithValue vs the new SqlParameter syntax the latter is preferable because you could exactly select the datatype and the size of the parameter passed to the database engine. In this way the database engine could better optimize the query and reuse the already prepared statement when you reexecute it. However the AddWithValue has its advantages in the simplicity and ease of use. So if you don't have worries about performance you could also use it.
By the way, the two syntax could be used in VB.NET and C#. They are part of the NET library that could be called from every managed language
When adding the parameter value, it depends on the data type being specified in the parameter. A normal example would be like the one which you can find on MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx.
So with regards to the extra M,L,#,& you do not need them any longer. Whenever I used AddWithValue, or adding a parameter, I always pass the values in double quotes.
I'm coding a GUI using WPF and Expression Blend for an application which is using SQLite as the database where to store its data.
I made several TextBox where the user can input the data they want to add or modify in the database. But if an user inputs the double quotes character an exception will be generated because I'm using the double quotes character in the queries for the strings.
So I'm looking for a way to prevent the user to introduce a double quote character directly. Is it possible?
Note: if relevant the implementation of SQLite in C# I'm using is csharp-sqlite.
You should be using parameterized queries rather than generating the SQL as a string and executing that string. There are quite a lot of things other than just double quotes that users could enter into the textbox that would break your query (just look up SQL injection as commented earlier) and using parameters solves all of the cases. If you try to handle every case yourself you WILL miss something, it's only a question of whether anyone figures it out or not.
I have a string
good overview of ESP's in more detail than you probably need.
While inserting into SQL table it is giving error. So I want replace apostrophe in the string with double apostrophe like
good overview of ESP''s in more detail than you probably need
How to manipulate this in c#?
Very easy:
string s = "good overview of ESP's in more detail than you probably need.";
string escaped = s.Replace("'","''");
Note: It is usually safer to use command parameters. Especially if the values of the input strings are not controlled by your code (i.e. user entries).
Use the Parameter object.
myCommand.InsertCommand.Parameters.Add("#myString", SqlDbType.VarChar, 200);
myCommand.InsertCommand.Parameters["#myString"].Value = #"good overview of ESP's in more detail than you probably need.";
I was working on this problem for ages. Do it on the client, replacing the single quote with two single quotes. This works if you are executing an sp with several varchar input parameters. The only problem with this is SQL injection i.e. people can see what you are up to on the client which is never a good thing. The only way round this is to use SQLparameters on the server, as they have said earlier.
String.Replace(String,String) should work fine. In this example, you'd want:
String.Replace("'", "''")
However, I don't think that that'll fix your issue. I imagine you're more appropriately looking for:
String.Replace("'", "\'")
The reason for this being that MySQL, and I'd imagine other versions of SQL, expect strings to be enclosed in single quotes.
myCommand.InsertCommand.Parameters.Add("#myString", SqlDbType.VarChar, 200);
myCommand.InsertCommand.Parameters["#myString"].Value
I'm building (c#) sql select commands strings on the fly using LIKE %somestring% conditions. In my search strings I want to be able to handle any character found on a standard PC (US) keyboard (including ~ ! # # % etc., alt-special chars not required but would be nice to have). I know that single quotes need to be doubled up and perhaps double quotes as well. What other string fixes might be required to ensure correct syntax?
No fixes required:
SqlCommand cmd = new SqlCommand("select * from Foo where Bar like #p", connection);
SqlParameter p = new SqlParameter();
param.ParameterName = "#p";
param.Value = pattern;
cmd.Parameters.Add(param);
Apart from doubling up single quotes (or using a parametrised query), will the user know that "_" and "%" are wildcards (any-character and zero-or-more-any-characters respectively), and that "[...]" creates a closure?
To escape those characters there are two routes
WHERE Foo LIKE '%xxx\%yyy%' ESCAPE '\'
or
WHERE Foo LIKE '%xxx[%]yyy%'
the second uses the side effect of creating a closure, and avoids having to use the ESCAPE (which in itself needs some thought to choose a character that does not conflict with the rest of the string, or is itself escaped where it occurs)
Note that using 'LIKE %somestring%' will usually require a table scan, and may therefore lead to performance problems - e.g. if you have millions of rows to be checked.
In SQL Server you can use sp_ExecuteSQL if you are generating WHERE clauses by string-concatenation - so that only fields that the user specifies criteria for are included. sp_ExecuteSQL will cache the query and, most times, improve performance. (please ask if that it relevant and you need help)