i'm creating a small application with .edmx for database connection.
inside my database i created a string with example value:
this is:\r\nA new line
when I call this value (in debug) i see the value changed to
this is:\\r\\nA new line
resulting in a wpf textbox showing
this is:\r\nA new line
instead of
this is:
A new line
Any thoughts over what i'm doing wrong here?
EDIT:
Windows 8.1
VS2013 Express
SQL Server Express (LocalDb)
The values are stored in the database via a t-SQL command. (I'm still in the startup of the project)
Insert into Atable
(ID, value)
VALUES
(1, 'this is:\r\nA new line')
Because in sql \r does not mean anything special. In c#, \r is the same as ascii character #10, which is unprintable. What you are trying to make is an "escape sequence", which only exist in c#.
If you create the escaped character in c# and save it to sql, it will read back just fine. But if you type the escape character in sql, it won't be what you expect.
So, in an sql query, you would do this:
select 'this is:' + CHAR(13) + CHAR(10) + 'A new line' -- same as "\n\r" in c#
In c#, it would be
string message = "this is\r\nAnew line"
Or, better, use the built in
string message = "this is" + Environment.NewLine + "A new line";
Related
string cmdTrainText = "INSERT INTO dbo.Event_Train(SCOPE_IDENTITY(), Train," +
"Barrel_Train, Fire_Truck, Tram, Beverage_Cart) " +
"VALUES(cbTrain, cbTBarrelTrain, cbTFire_Truck, cbTram, " +
"cbTBeverage_Cart)";
I am getting the following error
System.DataSqlClient.SqlException {"Incorrect syntax near '('."}
Everything compiles OK. I get this error when I run the Program.
I am using Visual Studio 2015.
I am trying to learn C#
Do I need to put something around SCOPE_IDENTITY()?
ScopeIdentity should be the first element inside the VALUES brackets and you then you have to write the column name instead at the first brackets! ScopeIdentity in this case seems to be a value and not a column name for me.
An edit would look like this (with proposed column name ScopeID):
string cmdTrainText = "INSERT INTO dbo.Event_Train(ScopeID, Train," +
"Barrel_Train, Fire_Truck, Tram, Beverage_Cart) " +
"VALUES(SCOPE_IDENTITY(), cbTrain, cbTBarrelTrain, cbTFire_Truck, " +
"cbTram, cbTBeverage_Cart)";
You cannot have a different number of values vs. number of fields; you have 6 fields and only 5 values. Furthermore, if you have an IDENTITY field the db will autoincrement it without your specifying a value for it. The SCOPE_IDENTITY is a return value to provide the last IDENTITY value generated by the db for your insert and for the scope of the action (read up on IDENTITY vs. SCOPE_IDENTITY).
unclosed quotation mark after the character string 'HD10'.
I have read a lot of solution for this error and it is clearly stated because of ('). However i have done search the greatness apostrophe in my sql.
select * from Voucher where VoucherNo like '%''%'
it came out nothing. This actually means something good. My data are great. But the bad news is, I still cant solve this.
I also did search any truncate or duplicate just, i dont know, hoping it shows somewhere even i know thats not what is about. And this shows no sign of truncate nor duplicate.
If anyone really knows something (beside of giving the same advice to do what i already done), it would help a lot. Thank you.
-----EDITTED-------
this is my program code
public override VoucherCollection GetVoucherWhere(string whereCondition)
{
VoucherCollection VoucherCollection = new VoucherCollection();
Database db = SqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("SP_SELECT_Voucher_WHERE");
db.AddInParameter(dbCommand, "whereExpression", DbType.String, " " + whereCondition);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
**I dont think the error come from the codes, as this program have been running for 2 years. However, it only came right after my client running a new voucher for a bonus. (And the person who run this thing have already transferred to a different department)
The where statement shows all the voucherno in DB.
The dbcommand shows the exception.
im using sql server 2008
Try
select * from Voucher where VoucherNo like '%''''%'
' is opening/closing string char so when you want ' in between string, you will
need escape sequence that is other ' char
for 2 ' chars, two esc char '
ie. ''''
I was getting this error: "Input string was not in a correct format."
Here is my Code:
private void UpdatePOdetailBalance(int Qty)
{
int newbal;
SqlCommand com = new SqlCommand();
com.Connection = cn;
newbal = Convert.ToInt16(txtQtyOrdered.Text) - Qty;
com.CommandText =
"UPDATE PODetail SET BalanceQty="+ newbal +" WHERE OrderID=" +
Convert.ToInt16(txtPONumber.Text) + "AND ItemID=" +
Convert.ToInt16(txtItemNo.Text);
com.ExecuteNonQuery();
}
private void btnOK_Click(object sender, EventArgs e)
{
UpdatePOdetailBalance(Convert.ToInt16(txtQuantity.Text));
}
I want to compute the newbal which is equal to txtQtyOrdered minus Qty but i'm getting this error please help me with this. Thanks.
The problem stated by your error message is probably on one of the lines that try to convert the value in the textboxes to a short integer. Without any check, the value typed by your user could be anything but a number and you get this error message (for example, if you user leaves the textboxes empty).
You should try to check if the textboxes content could be converted to a valid short integer using TryParse before attempting to execute the query
int ordered;
if(!int16.TryParse(txtQtyOrdered.Text, out ordered))
{
MessageBox.Show("Invalid number for Ordered quantity");
return;
}
int orderID;
if(!int16.TryParse(txtPONumber.Text, out orderID))
{
MessageBox.Show("Invalid number for OrderId");
return;
}
int itemID;
if(!int16.TryParse(txtItemNo.Text, out itemID))
{
MessageBox.Show("Invalid number for ItemID");
return;
}
At this point you could execute your calculation using the converted short integers and then write your query in this way (adding a space before the AND)
com.CommandText =
"UPDATE PODetail SET BalanceQty="+ newbal.ToString() +
" WHERE OrderID=" + orderID.ToString() +
" AND ItemID=" + itemID.ToString();
But the string concatenation of query text and user input is never advised as a good practice (in your case is harmless because if the conversion is successful you don't have to worry about Sql Injection, but don't take the habit to do it).
So the perfect way to write this query is through the use of a parametrized query
com.CommandText =
"UPDATE PODetail SET BalanceQty=#newbal " +
" WHERE OrderID=#orderID " +
" AND ItemID= #itemID"
com.Parameters.AddWithValue("#newbal", newBal);
com.Parameters.AddWithValue("#orderID", orderID);
com.Parameters.AddWithValue("#itemID", itemID);
com.ExecuteNonQuery();
As a good article on Parameterized query and why to use them, I suggest to read these old words from Jeff Atwood
You need to put a space before your "AND" and that you are trying to convert a string to an integer that isn't an integer.
I'd recommend making changes according to the following code review suggestions based on the code (listed in order of value (cost/benefit of "fixing")):
This method, which is accessing a database should not be reading controls to get its values. Instead there should be an event handler, such as a button click, that parses the values of other controls, using TryParse, as gregjer answered. By segregating the UI and Data code, the data access layer is easier to test and by parsing at the surface (the UI layer) exceptions dealing with bad user input will be caught as soon as possible.
Dynamic SQL via strings in the database or in the data access layer w/i .NET is open to SQL injection. You are resolving that issue by parsing the text, so awesome job by you. BUT, this was already handled by the .NET team by providing parameterized commands. Refer to the MSDN SqlCommand.Parameters or see here for a brief, including how a consuming developer groks this topic: When should "SqlDbType" and "size" be used when adding SqlCommand Parameters?
Variable naming. Instead of Qty, standard .NET naming conventions would call for quantity, camelCased since it is a parameter and the full human language name, not a shorthand or abbreviation, especially for publicly visible bits. IntelliSense makes long variable names not a problem. Since .NET is unwieldy using just Notepad, it should be assumed that other developers are using an IDE such as VisualStudio or SharpDevelop, so use meaningful names.
Stored procedures should be used. Every time this SQL is executed, SQL Server needs to check its command cache minimally, but if the command has been flushed from cache, the SQL command needs to be interpreted and encached (put into cache). This as well as the fact that using a stored procedure requires "shipping" less bytes on every call to the database.
That error means that the string you're trying to convert is not an integer.
Try to use int.TryParse
int newbal;
if(int.TryParse(txtQtyOrdered.Text, out newbal))
newbal = newbal - Qty;
the same with other texts you are trying to convert
... and add space before " AND which will generate next error
I think you need to debug your code. During debugging copy your query from "com.CommandText" and paste in SQL Server you find the error
There is only a query error nothing else...
May be txtQtyOrdered value is not integer, there is also need blank space "AND ItemID=" to " AND ItemID="
Thanks,
Taha
First - You are missing a space before "AND"
You should try to parse the values before the update statement.
You should decide what you want to do in case the input from the textbox wasn't in the correct format rather then just get an exception when you try to update.
This isn't the right way to format strings, You should use string.Format
you can sometimes run into this problem when you have multiple parameters and are using Oracle or DB2 databases. They dont's support named parameters or it's not turned on.
Oracle:
Dim cmd As OracleCommand = DirectCast(connection.CreateCommand, OracleCommand)
cmd.BindByName = True
Make sure you parameters are added to the command object in the same order as the sql statement
I have an existing database with existing data that I can't change it's structure or values.
In that database there is a nvarchar column that contains values in the twilight unicode zone starting with F800, upward.
When I select those values in SQL or use SQL function, unicode - I get the proper values.
When I select the same values in .Net - I get an error value - all the values in that twilight zone become 65533.
I need those values - how can I presuade .Net to give me those values - something like chaninging the connection encoding to a custom one - or ucs-2 etc...
Here is a sample code that demonstraits the problem:
c.CommandText = "select NCHAR(55297)";
using (var r = c.ExecuteReader())
{
r.Read();
var result = r[0]; //expected 55297 but got 65533
}
55297 is D801 which isn't defined? you probably want f801 which is 63489? But it appears as if that one isn't defined either. Which characters do you want?
If I try doing a "select NCHAR(55297)" in SQL Server Management studio, I get back the diamond question mark, but if I do "select NCHAR(63489)" I get back a dot of some sort:
If what you want is the character values, you can ask for them directly:
select Unicode(NCHAR(63489))
This returns 63489 (as an integer)
If you want them as a byte array, you can ask for that:
select CONVERT(varbinary(MAX), FieldThatIsAnNvarchar) from ThatTable
After much investigations I failed to find any way around this. I couldn't find any two way conversion that would work here.
It seems that some unicode values are intended for some strange unicode scenario that isn't supported by .Net, but is partially supported in a way that breaks what we need here.
I'm working on my first database application. It is a WinForms application written in C# using a SQLite database.
I've come across some problems, when a apostrophe is used, my SQLite query fails. Here is the structure of my queries.
string SQL = "UPDATE SUBCONTRACTOR SET JobSite = NULL WHERE JobSite = '" + jobSite + "'";
For instance, if an apostrophe is used in the jobSite var, it offsets the other apostrophes in the command, and fails.
So my questions are:
1. How do I escape characters like the apostrophe and semicolon in the above query example?
2. What characters do I need to escape? I know I should escape the apostrophe, what else is dangerous?
Thanks for your help!
Rather use Parameters
There is a previous stack-overflow question about it
Adding parameters in SQLite with C#
if you need more functionality you can also use Entity Framework
http://sqlite.phxsoftware.com/
Sorry not to familiar with the Syntax but the concept should same.
Something like :
SQLiteCommand Command = "UPDATE SUBCONTRACTOR SET JobSite = NULL WHERE JobSite = #JobSite";
Command.Parameters.Add(new SQLiteParameter("#JobSite", JobSiteVariable));
command.ExecuteNonQuery();
to escape an apostrophe add another apostrophe...
so a string like it's should be inserted as it''s
You may also need to escape quotation marks. The way to do this is to use a backslash as an escape charater...
like so... 'and he said\"escape all those quotes\"'
You should also beware of SQL injections... depending on the type of programming language you are using there exist different functions that can help clean out any malicious code.
C# tutorial on SQL Injections for example
You should never concatenate strings to build SQL queries for SQLite - or for any other SQL DB if possible. It makes your code fragile and opens up potential entry points for injection attacks.
The proper way to do it is to use hosted parameters. This approach removes the need for cumbersome string filtering. I am not sure how to do that in C# for SQLite but any decent language binding for SQLite should allow you to use hosted parameters.