Update query for Access Database for certain Parameters - c#

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.

Related

error with Scope_Identity when trying to insert in 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).

Data type mismatch in criteria expression with REPLACE and nothing to replace

EDIT: I've solved my problem by switching to ACE instead of ODBC. Likely this was some bug with ODBC? In any case, this seems like the solution if using ACE is an option for you.
Putting this up here because stackoverflow is not allowing me to answer my own question so soon after asking.
My adapter is throwing a "Data type mismatch in criteria expression." exception when trying to fill a DataTable with the query:
"SELECT updateTime AS [Time], updateType AS [Type], updateOperator AS [Operator], REPLACE(updateText, '\\n', '\\r\\n') AS [Update] FROM [updt] WHERE updID = '" + updID + "'"
The REPLACE function is used to make the newlines use the Windows style so that they display correctly in DataGridViews and other winforms controls.
The database is Access 2010
I am connecting via ODBC (not Jet)
The datatype of updID is correct, it is 'Text'.
The problem occurs when trying to grabs rows where 'updateText' has no \n characters to replace. For any row that has '\n', it will function correctly.
Yet, when the program breaks from the exception, I can open the command object and take the command text and run it in Access without any problems.
Thanks
enclose that field in an iif() function. basically if it is not null then do the replace. Otherwise keep it null.
You might need an IIF function as Replace function cannot handle Null.
"SELECT updateTime AS [Time], updateType AS [Type], updateOperator AS [Operator], " & _
"REPLACE(IsNull(updateText, "", updateText), '\\n', '\\r\\n') AS [Update] " & _
"FROM [updt] WHERE updID = '" + updID + "'"
Why don't you replace the text first and then include in your query.
string strValue;
if(updateText.Contains("\r"))
strValue=updateText.Replace("\n","\r\n");
else
strValue==updateText;
"SELECT updateTime AS [Time], updateType AS [Type], updateOperator AS [Operator],"+
strValue "+ AS [Update] FROM [updt] WHERE updID = '" + updID + "'"
Hope it helps.
I've solved my problem by switching to ACE instead of ODBC. Likely this was some bug with ODBC? In any case, this seems like the solution is using ACE is an option for you.

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

Error on Inserting data into database

I have 3 Textboxes called, TxtFirstName, TxtMiddleName and TxtLastName. I would like to insert this info to the database where my column name is just FullName. I would want my 3 Information to join to insert them into one. What I did is :
string _fullname = _lastname + "," + _firstname + middlename;
cmd = new SqlCommand("INSERT INTO TableVote (FullName) VALUES ('" + _fullname + "')", sc);
but it seems that it gets me an error.
"String or Binary data would be truncated. The Statement has been terminated."
How do i correct this ?
The error means that your string is longer than the maximum length allowed for the column. You either need to adjust your schema to allow longer values or truncate the value you insert.
Also: You should really use parametrized commands:
cmd = new SqlCommand("INSERT INTO TableVote (FullName) VALUES (#fullname)");
cmd.Parameters.AddWithValue("#fullname", _fullname);
Read up on Sql Injection attacks.
Update: As mentioned by others you should contemplate storing the name in different columns (i.e. FirstName, MiddleName, LastName. Otherwise you throw away information which will be hard to recompute (e.g. try making a statistic of the most common middle name with your schema).
As already noted, the value you are inserting into your table is too long for the column specification.
HOWEVER
I've been working with databases for quite a while now, and I'd like to advise you to please not store the name all in one column. I've seen this over and over again. It seems like a good, quick idea at the time, but sooner or later, you'll have a requirement where you need to get just part of the name. Once you reach that point, you'll find yourself with all kinds of problems, because names are very, very complicated things that are highly dependent on language and culture. Given a list of whole names, think about how you would parse out just the last names. At first, it seems very simple, until you consider all the special cases, like people with two last names ("Harper-Smith"), last names from other cultures ("St. James", "O'Connell", "Van der Wall"), etc.
Just consider saving the name in three parts in three columns, it doesn't take much and it will save you a lot of trouble later.

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.

Categories

Resources