error with Scope_Identity when trying to insert in C# - c#

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).

Related

ORA-20000: Oracle Text error: DRG-10599: column is not indexed

Hello I cant really make this sql workin because error column is not indexed (when i was using just like "=" it was all right) but I need contains for lazy typing purposes. I was searching the net, but the examples are always on so much different concept, than I have here. Can someone make example for this sql, how to make index please? the TextBox1.Text is inserted value of last name by user.
SELECT * FROM v_employees_intr
where CONTAINS(NLSSORT(LAST_CZ, 'NLS_SORT = hungarian_ai'), NLSSORT('%" + TextBox1.Text + "%', 'NLS_SORT = hungarian_ai'))>0
ORDER BY " + RadioButtonList1.SelectedValue.ToString() + " ASC"
How to create a Text index? I tried to
CREATE INDEX myindex ON docs(text) INDEXTYPE IS CTXSYS.CONTEXT
Because Oracle web site says it is basic for contains(). But this error message pop out ORA-02158: invalid CREATE INDEX option. So I tried to add the ; on end like IS CTXSYS.CONTEXT; and there then goes ORA-00911: invalid character error. Please can someone help me create index for my query?
You should try with:
CREATE INDEX myindex ON v_employees_intr(LAST_CZ) INDEXTYPE IS CTXSYS.CONTEXT;

place database string value with \r\n into wpf textbox

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";

C# error : Input string was not in a correct format

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

ASP.NET Queries not changing with strings and paramters

I am running queries as a string that has a single parameter (and is changed) but am getting some odd behavior. Here is the code:
String cmd = "SELECT RID FROM SCHEMAS
WHERE NAMESPACE_PREFIX = '" + prefix + "' AND GENERIC_SCHEMA = 1";
Response.Write(cmd + "<br>");
using (SqlDataReader elementReader = elementDB.executeCommand(cmd))
{
while (elementReader.Read())
{
Response.Write(cmd+ elementReader["RID"].ToString() + "<br>");
}
}
What I expect to happen:
The Response.Write executes two times and the the data is identical.
What is actually happening:
The elementReader appears to 'memorize' the first value of prefix.
When the 'prefix' variable changes, the Response.Write outside the
SQL statement is correctly outputting the string, however the while
loop inside the SQL statement does not execute at all. However,
whenever 'prefi'x comes back to the first value it was set to, the
statement DOES execute.
I am at a complete loss as to why this is happening and would appreciate help. Thanks.
The most likely cause is two records in the database with the same NAMESPACE_PREFIX.
Maybe you need a unique index on that field.

Update query for Access Database for certain Parameters

I am using MS Access as a database and using c#, .net for updating some records in it. But it is giving error saying
"No value given for one or more required parameters."
There are 5 colums in Table and I want to update only 2, for that I have written the query like
"update User_DTL set user_role_id = '" + _UserRole + "', auth_id ='" + _authId + "'"
+ " WHERE Id = '" + _Id + "' ";
where _UserRole, _authId, _Id are strings.
What may be the error. Do I need to give every parameter in update statement or there is some other way.
Thanks
Whenever you encounter such an error, stick a breakpoint in and examine your query to ensure it looks as you expect. For example, is there actually a _UserRole, _authId and _Id present in the query.
You could also add some defensive code to check them before you prepare the statement - this example checks to make sure the _UserRole isn't null or empty.
if (!string.IsNullOrEmpty(_UserRole)) { ...
Hard to say without seeing your code, but based on the error message I'm guessing one of the following:
1) One of the following fields does not exist in User_DTL: user_role_id, auth_id, Id
2) _UserRole, _authId, _Id contains a single-quote character.
The best way to troubleshoot this is to print the actual concatenated query string and then open a SQL Query in Access and run it. It should be pretty obvious what the problem is then.
BTW: You likely have some SQL Injection vulnerabilities with this code.

Categories

Resources