My goal is to update the QTY for each SKU. I am using a SqlDataAdapter to accomplish this. The program runs fine. Just that no result happens.
QUESTION: Why is no result happening? My database remains unchanged.
Code below
public static void updateInventoryfromAMZ(DataTable datatable)
{
int index = 0;
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString();
DataSet amzInventoryDataSet = new DataSet("AMZINVDATASET");
amzInventoryDataSet.Tables.Add(datatable);
// FOR EACH ROW - PERFORM AN UPDATE //
using (SqlConnection connection = new SqlConnection(connString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
foreach (DataRow row in amzInventoryDataSet.Tables[index].Rows)
{
string sku = datatable.Rows[index]["seller-sku"].ToString();
string qty = datatable.Rows[index]["quantity"].ToString();
// Create the UpdateCommand.
SqlCommand command = new SqlCommand(
"UPDATE Inventory SET qty = #qty" +
"WHERE sku = #sku", connection);
// Add the parameters for the UpdateCommand.
command.Parameters.Add("#qty", SqlDbType.Int, qty.Length, qty);
command.Parameters.Add("#sku", SqlDbType.VarChar, sku.Length, sku);
adapter.UpdateCommand = command;
adapter.Update(amzInventoryDataSet.Tables[index]);
index++;
}
}
}
When you concatenating two sql strings, you better add space at the end of first string or at the beginning of second string. As Gordon Linoff pointed out your sql statement is incorrect. And also setting parameters and the values need to be change depending on the type of the parameters.
try below code, I have use SqlCommand and ExecuteNonQuery method to update each row data
using (SqlConnection connection = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("UPDATE Inventory SET qty = #qty WHERE sku = #sku", connection))
{
connection.Open();
var paramqty= cmd.Parameters.Add("#qty", SqlDbType.Int);
var parasku = cmd.Parameters.Add("#sku", SqlDbType.VarChar);
foreach (DataRow row in amzInventoryDataSet.Tables[0].Rows)
{
parasku.Value = row["seller-sku"].ToString();
paramqty.Value = int.Parse(row["quantity"].ToString());
cmd.ExecuteNonQuery();
}
}
I am thinking your problem are these lines:
"UPDATE Inventory SET qty = #qty" +
"WHERE sku = #sku", connection);
They are going to produce a string like:
"UPDATE Inventory SET qty = #qtyWHERE sku = #sku", connection);
And the variable #qtyWHERE is not defined.
Try this instead:
"UPDATE Inventory SET qty = #qty WHERE sku = #sku", connection);
Related
I am trying to store sql data that I have for a voucher id and voucher amount into a variable and display it into a label on a click of a button.
protected void Button1_Click(object sender, EventArgs e)
{
string voucherId = String.Empty;
string voucherAmount = String.Empty;
string queryVoucherId = "select voucherid from ReturnForm where email = '" + Session["username"] + "';";
string queryVoucherAmount = "select voucheramount from ReturnForm where email = '" + Session["username"] + "';";
int index = 0;
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherId, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherId = reader[index].ToString();
index++;
}
}
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherAmount, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherAmount = reader[index].ToString();
index++;
}
}
if (txtVoucher.Text == voucherId)
{
Label3.Visible = true;
Label3.Text = voucherAmount;
}
}
When I click the button its giving me an error saying that the index is out of bounds.
Building on #JSGarcia's answer - but using parameters as one ALWAYS should - you'd get this code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom WHERE Email = #email";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
// set the parameter before opening connection
// this also defines the type and length of parameter - just a guess here, might need to change this
cmd.Parameters.Add("#email", SqlDbType.VarChar, 100).Value = email;
conn.Open();
sda.Fill(dt);
conn.Close();
}
Personally, I'd rather use a data class like
public class VoucherData
{
public int Id { get; set; }
public Decimal Amount { get; set; }
}
and then get back a List<VoucherData> from your SQL query (using e.g. Dapper):
string query = $"SELECT Id, Amount FROM ReturnFrom WHERE Email = #email";
List<VoucherData> vouchers = conn.Query<VoucherData>(query).ToList();
I'd try to avoid the rather clunky and not very easy to use DataTable construct...
I strongly recommend combining your sql queries into a single one, write it into a datatable and continue your logic from there. IMHO it is much cleaner code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom where Email = '{email}'";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = conn.CreateCommand())
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
conn.Open();
sda.Fill(dt);
conn.Close();
}
// Work with DataTable dt from here on
...
Well, one more big tip?
You ONLY as a general rule need a dataadaptor if you going to update the data table.
And you ONLY need a new connection object if you say not using the sql command object.
The sqlcommand object has:
a connection object - no need to create a separate one
a reader - no need to create a separate one.
Note how I did NOT create a seperate connection object, but used the one built into the command object.
And since the parameter is the SAME in both cases? Then why not re-use that too!!
So, we get this:
void TestFun2()
{
String str = "some conneciton???";
DataTable rstVouch = new DataTable();
using (SqlCommand cmdSQL =
new SqlCommand("select voucherid from ReturnForm where email = #email",
new SqlConnection(str)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = Session["username"];
cmdSQL.Connection.Open();
rstVouch.Load(cmdSQL.ExecuteReader());
// now get vouch amount
cmdSQL.CommandText = "select voucheramount from ReturnForm where email = #email";
DataTable rstVouchAmount = new DataTable();
rstVouchAmount.Load(cmdSQL.ExecuteReader());
if (rstVouch.Rows[0]["vourcherid"].ToString() == txtVoucher.Text)
{
Label3.Visible = true;
Label3.Text = rstVouchAmount.Rows[0]["voucheramount"].ToString();
}
}
}
I'm trying to update values of two tables such as from dataGridview
Order table and Orderdetail table as shown in my image.
It's working to update Order table but updating OrderdDetail table is not working. I want to update all rows with the same OrderNr. I get OrderDetail values from dataGridView. Here is my code:
private void UpdateOrder(int paymentTypes)
{
try
{
string connstring = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("UPDATE [Orders] SET Amount = #Amount, Tax = #Tax , ToPay = #ToPay WHERE OrderNr = #OrderNumber", conn))
{
// This First table Orders updating fine
cmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
cmd.Parameters.AddWithValue("#Tax", txtTax.Text);
cmd.Parameters.AddWithValue("#ToPay", txtToPay.Text);
cmd.ExecuteNonQuery();
}
// Here begin for OrderDetails table and not working to update.
foreach (DataGridViewRow row in dgvCart.Rows)
{
using (OleDbCommand cmd = new OleDbCommand("UPDATE [OrdersItems] SET OrderNr = #OrderNumber, ProductId = #ProductId, Quantity = #Quantity, WHERE OrderNr = #OrderNumber AND ProductId = #ProductId", conn))
{
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Updating successfully !", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
There are a couple of errors in your code.
First you have a syntax error in your query
using (OleDbCommand cmd = new OleDbCommand(#"UPDATE [OrdersItems]
SET OrderNr = #OrderNumber, ProductId = #ProductId, Quantity = #Quantity,
WHERE OrderNr = #OrderNumber AND ProductId = #ProductId", conn))
There is a comma before the WHERE statement that you should remove.
Second, the first query is missing the parameter for OrderNumber.
Third point.
In OleDb parameters are positional, even if you can name them you should put them in the same order in which they appear in the query and you need to put it again if you use them two times (OrderNumber & ProductID appear both in the SET part and in the WHERE)
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
However you don't need to update the ProductID and the OrderNumber. They cannot change otherwise this query could not find the rows that you want to update.
using (OleDbCommand cmd = new OleDbCommand(#"UPDATE [OrdersItems]
SET Quantity = #Quantity
WHERE OrderNr = #OrderNumber AND ProductId = #ProductId", conn))
with only three parameters in the correct order
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
I'm not very good but I'm trying. I think there is something I don't understand somewhere...
I'm trying to get statistique from a DB like how many row got "X". Look simple. I know the SQL statement for it. There is a lot of walkthrough around. But I don't know how to make it appear on a page.
if(!Request.QueryString["RNum"].IsEmpty() ) {
searchTerm = Request.QueryString["RNum"];
selectCommand2 = "SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl = #0";
}
var Count = db.QueryValue(selectCommand2, searchTerm);
With a submit button to send the query how can I make it appear on a page?
just try this
searchTerm = Request.QueryString["RNum"];
string sqlSelect = "SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl= #NoEmpl";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
// Set SqlDbType based on your DB column Data-Type
sqlCommand.Parameters.Add("#NoEmpl", System.Data.SqlDbType.Varcahr);
sqlCommand.Parameters["#NoEmpl"].Value = searchTerm ;
OR
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl= #NoEmpl", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("#NoEmpl", searchTerm ));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
//read here
}
}
I'm using a query to update a column value on table and also retrieve the updated value using the following way on the ASP.NET site. Is there any way to use single query instead of double queries as below?
using (SqlConnection connection = new SqlConnection(connStr)){
string updateUserQuery = "Update user_master set login_failed_attempts = login_failed_attempts + 1 where id = #id; Select #login_failed = login_failed_attempts from user_master where id = #id";
SqlCommand cmd = new SqlCommand(updateUserQuery, connection);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = user_id;
SqlParameter outputIdParam = new SqlParameter("#login_failed", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(outputIdParam);
cmd.ExecuteNonQuery();
int loginFailedAttempts = int.Parse(outputIdParam.Value.ToString());
}
Updated code is given below after Matthew's answer.
string updateUserQuery = "Update user_master set login_failed_attempts = login_failed_attempts + 1 OUTPUT INSERTED.login_failed_attempts where id = #id";
SqlCommand cmd = new SqlCommand(updateUserQuery, connection);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = user_id;
int loginFailedAttempts = (int)cmd.ExecuteScalar();
Use an OUTPUT clause.
UPDATE user_master
SET login_failed_attempts = login_failed_attempts + 1
OUTPUT INSERTED.login_failed_attempts
WHERE id = #id
Then change your ExecuteNonQuery to an ExecuteScalar and use the result from that accordingly.
You could also change it to an ExecuteReader and pull back multiple records, but given your use of #id I'm assuming you don't want that.
I wrote some code that takes some values from one table and inserts the other table with these values.(not just these values, but also these values(this values=values from the based on table))
and I get this error:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.`
here's the code. I don't know what i've missed.
string selectedItem = comboBox1.SelectedItem.ToString();
Codons cdn = new Codons(selectedItem);
string codon1;
int index;
if (this.i != this.counter)
{
//take from the DataBase the matching codonsCodon1 to codonsFullName
codon1 = cdn.GetCodon1();
//take the serialnumber of the last protein
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
dr.Read();
index = dr.GetInt32(0);
//add the amino acid to tblOrderAA
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) "
+ " values (?, ?)";
using (OleDbCommand command = new OleDbCommand(insertCommand, connection))
{
connection.Open();
command.Parameters.AddWithValue("orderAASerialPro", index);
command.Parameters.AddWithValue("orderAACodon1", codon1);
command.ExecuteNonQuery();
}
}
}
EDIT:I put a messagebox after that line:
index = dr.GetInt32(0);
to see where is the problem, and I get the error before that. I don't see the messagebox
Your SELECT Command has a syntax error in it because you didn't enclose it with quotes.
Change this:
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
to
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = ?";
OleDbCommand getSerial = new OleDbCommand(last, conn);
getSerial.Parameters.AddWithValue("?", this.name);
OleDbDataReader dr = getSerial.ExecuteReader();
This code is example from here:
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try to do the same as in the example.