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.
Related
I am generating SQL code for different types of databases. To do that dynamically, certain parameters of the SQL script are stored in variables.
One such stored parameter is the comparison expression for certain queries.
Lets say I have a Dogs table with a Name, DateOfBirth and Gender columns, then I have comparison expressions in a variable such as:
string myExpression = "Gender=1";
string myExpression2 = "Gender=1 AND Name='Bucky'";
I would build the following SQL string then:
string mySqlString = "SELECT * FROM "dbo"."Dogs" WHERE " + myExpression;
The problem is, that for Oracle syntax, I have to quote the column names (as seen at dbo.Dogs above). So I need to create a string from the stored expression which looks like:
string quotedExpression = "\"Gender\"=1";
Is there a fast way, to do this? I was thinking of splitting the string at the comparison symbol, but then I would cut the symbol itself, and it wouldn't work on complex conditions either. I could iterate through the whole string, but that would include lot of conditions to check (the comparison symbol can be more than one character (<>) or a keyword (ANY,ALL,etc.)), and I rather avoid lots of loops.
IMO the problem here is the attempt to use myExpression / myExpression2 as naked SQL strings. In addition to being a massive SQL-injection hole, it causes problems like you're seeing now. When I need to do this, I treat the filter expression as a DSL, which I then parse into an AST (using something like a modified shunting yard algorithm - although there are other ways to do it). So I end up with
AND
=
Gender
1
=
Name
'Bucky'
Now I can walk that tree (visitor pattern), looking at each. 1 looks like an integer (int.TryParse etc), so we can add a parameter with that value. 'Bucky' looks like a string literal (via the quotes), so we can add a string-based parameter with the value Bucky (no quotes in the actual value). The other two are non-quoted strings, so they are column names. We check them against our model (white-list), and apply any necessary SQL syntax such as escaping - and perhaps aliasing (it might be Name in the DSL, but XX_Name2_ChangeMe in the database). If the column isn't found in the model: reject it. If you can't understand an expression completely: reject it.
Yes, this is more complex, but it will keep you safe and sane.
There may be libraries that can already do the expression parsing (to AST) for you.
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.
E.g:
isValidCppIdentifier("_foo") // returns true
isValidCppIdentifier("9bar") // returns false
isValidCppIdentifier("var'") // returns false
I wrote some quick code but it fails:
my regex is "[a-zA-Z_$][a-zA-Z0-9_$]*"
and I simply do regex.IsMatch(inputString).
Thanks..
It should work with some added anchoring:
"^[a-zA-Z_][a-zA-Z0-9_]*$"
If you really need to support ludicrous identifiers using Unicode, feel free to read one of the various versions of the standard and add all the ranges into your regexp (for example, pages 713 and 714 of http://www-d0.fnal.gov/~dladams/cxx_standard.pdf)
Matti's answer will work to sanitize identifiers before inserting into C++ code, but won't handle C++ code as input very well. It will be annoying to separate things like L"wchar_t string", where L is not an identifier. And there's Unicode.
Clang, Apple's compiler which is built on a philosophy of modularity, provides a set of tokenizer functions. It looks like you would want clang_createTranslationUnitFromSourceFile and clang_tokenize.
I didn't check to see if it handles \Uxxxx or anything. Can't make any kind of gurarantees. Last time I used LLVM was five years ago and it wasn't the greatest experience… but not the worst either.
On the other hand, GCC certainly has it, although you have to figure out how to use cpp_lex_direct.
I have the following line of code:
var connectionString = configItems.
Find(item => item.Name.ToLowerInvariant() == "connectionstring");
VS 2010 code analysis is telling me the following:
Warning 7 CA1308 : Microsoft.Globalization : In method ... replace the call to 'string.ToLowerInvariant()' with String.ToUpperInvariant().
Does this mean ToUpperInvariant() is more reliable?
Google gives a hint pointing to CA1308: Normalize strings to uppercase
It says:
Strings should be normalized to uppercase. A small group of characters, when they are converted to lowercase, cannot make a round trip. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters.
So, yes - ToUpper is more reliable than ToLower.
In the future I suggest googling first - I do that for all those FxCop warnings I get thrown around ;) Helps a lot to read the corresponding documentation ;)
Besides what TomTom says, .net is optimized for string comparison in upper case. So using upper invariant is theoretically faster than lowerinvariant.
This is indeed stated in CLR via C# as pointed out in the comments.
Im not sure if this is of course really true since there is nothing to be found on MSDN about this topic. The string comparison guide on msdn mentions that toupperinvariant and tolowerinvariant are equal and does not prefer the former.
I am wondering if it is possible to extract the index position in a given string where a Regex failed when trying to match it?
For example, if my regex was "abc" and I tried to match that with "abd" the match would fail at index 2.
Edit for clarification. The reason I need this is to allow me to simplify the parsing component of my application. The application is an Assmebly language teaching tool which allows students to write, compile, and execute assembly like programs.
Currently I have a tokenizer class which converts input strings into Tokens using regex's. This works very well. For example:
The tokenizer would produce the following tokens given the following input = "INP :x:":
Token.OPCODE, Token.WHITESPACE, Token.LABEL, Token.EOL
These tokens are then analysed to ensure they conform to a syntax for a given statement. Currently this is done using IF statements and is proving cumbersome. The upside of this approach is that I can provide detailed error messages. I.E
if(token[2] != Token.LABEL) { throw new SyntaxError("Expected label");}
I want to use a regular expression to define a syntax instead of the annoying IF statements. But in doing so I lose the ability to return detailed error reports. I therefore would at least like to inform the user of WHERE the error occurred.
I agree with Colin Younger, I don't think it is possible with the existing Regex class. However, I think it is doable if you are willing to sweat a little:
Get the Regex class source code
(e.g.
http://www.codeplex.com/NetMassDownloader
to download the .Net source).
Change the code to have a readonly
property with the failure index.
Make sure your code uses that Regex
rather than Microsoft's.
I guess such an index would only have meaning in some simple case, like in your example.
If you'll take a regex like "ab*c*z" (where by * I mean any character) and a string "abbbcbbcdd", what should be the index, you are talking about?
It will depend on the algorithm used for mathcing...
Could fail on "abbbc..." or on "abbbcbbc..."
I don't believe it's possible, but I am intrigued why you would want it.
In order to do that you would need either callbacks embedded in the regex (which AFAIK C# doesn't support) or preferably hooks into the regex engine. Even then, it's not clear what result you would want if backtracking was involved.
It is not possible to be able to tell where a regex fails. as a result you need to take a different approach. You need to compare strings. Use a regex to remove all the things that could vary and compare it with the string that you know it does not change.
I run into the same problem came up to your answer and had to work out my own solution. Here it is:
https://stackoverflow.com/a/11730035/637142
hope it helps