Insert SQL statement is not working after checking against quantities from tables in database - sql

I created a sale table which Insert function does not work properly. It shows the error message
Must declare the scalar variable "#iProductID"
at the statement
using (var sdRead = cmdOrder.ExecuteReader())
I am really stuck here. I also want to know how I can achieve for inserting SaleID with auto-increment without with any input field at the form. Every time I insert a new record, SaleID should be auto-generated and saved in the database.
My code below work like this. I checked available stocks from my Product table. If quantity order is greater than quantity from Product table, show error message.
Otherwise, proceed to inserting order information into Sale table. Any help is appreciated.
private void btnOrder_Click(object sender, EventArgs e)
{
int iQuantityDB;
int iCustomerID = Convert.ToInt32(txtCustomerID.Text);
int iProductID = Convert.ToInt32(txtProductID.Text);
decimal dPrice = Convert.ToDecimal(txtPrice.Text);
int iQuantity = Convert.ToInt32(txtQuantity.Text);
decimal dSubtotal = Convert.ToDecimal(txtSubTotal.Text);
decimal dGST = Convert.ToDecimal(txtGST.Text);
decimal dTotal = Convert.ToDecimal(txtTotal.Text);
string strConnectionString = #"Data Source = KK\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = JeanDB; MultipleActiveResultSets=True;";
using (var sqlconn = new SqlConnection(strConnectionString))
{
sqlconn.Open();
string querySelectQuantity = #"Select Quantity from dbo.JeanProduct WHERE ProductID = #iProductID";
using (var cmdOrder = new SqlCommand(querySelectQuantity, sqlconn))
{
using (var sdRead = cmdOrder.ExecuteReader())
{
sdRead.Read();
iQuantityDB = Convert.ToInt32(sdRead["Quantity"]);
}
}
if (iQuantityDB > iQuantity)
{
string InsertQuery = #"INSERT INTO Sale(CustomerID, ProductID, Price, Quantity, Subtotal, GST, Total)VALUES(#iCustomerID, #iProductID, #dPrice, #iQuantity, #dSubtotal, #dGST, #Total)";
using (var InsertCMD = new SqlCommand(InsertQuery, sqlconn))
{
InsertCMD.Connection = sqlconn;
InsertCMD.Parameters.AddWithValue("#iCustomerID", iCustomerID);
InsertCMD.Parameters.AddWithValue("#iProdcutID", iProductID);
InsertCMD.Parameters.AddWithValue("#dPrice", dPrice);
InsertCMD.Parameters.AddWithValue("#iQuantity", iQuantity);
InsertCMD.Parameters.AddWithValue("#dSubtotal", dSubtotal);
InsertCMD.Parameters.AddWithValue("#dGST", dGST);
InsertCMD.Parameters.AddWithValue("#dTotal", dTotal);
InsertCMD.ExecuteNonQuery();
LoadDataonTable();
}
}
else
{
MessageBox.Show("no more stock");
}
sqlconn.Close();
}
}

At the line using (var sdRead = cmdOrder.ExecuteReader()) your SQL SELECT query is using a parameter - WHERE ProductID = #iProductID - but this hasn't been set. Hence the error message Must declare the scalar variable "#iProductID"
Just add cmdOrder.Parameters.AddWithValue("#iProductID", iProductID) between defining the SQL and executing it, and that should clear that problem.
Moving on to the next one - you're using AddWithValue("#dTotal" but it's #Total in the SQL :)

Related

How to convert values of a datatable from string to integer

I'm making a fine calculator in a library system. In it,I need to calculate the fine of a given day. For this,I use a data table to load the fine amounts and then,I need to calculate the total fine amount by adding each fine amount.But I'm having a problem in parsing the fine values which are in string format to integer.Here is a screenshot of the error.
Here is a screenshot of the error.
And here is the code which I used to convert the string values to integer and calculate the total fine.
int sum1 = 0;
int myNum;
String Display;
private void btnNext_Click(object sender, EventArgs e)
{
try
{
if (rbtnToday.Checked == true)
{
DateTime today = DateTime.Today;
Con.Open();
String select_today_query = "SELECT Fine FROM BookReceiveMem WHERE RecDate='" + today + "'";
Sqlda = new SqlDataAdapter(select_today_query, Con);
DataTable Dt = new DataTable();
Sqlda.Fill(Dt);
Con.Close();
foreach (DataRow row in Dt.Rows)
{
myNum = int.Parse(Dt.Columns[0].ToString());
sum1 = sum1 + myNum;
}
Display = sum1.ToString();
MessageBox.Show("Today Fine Amount is= " + Display, "Today Fine Calculation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Is there any method to solve this problem?
Databases are really good at calculating things like a sum. If Fine is an integer in your database you can get it to sum all the rows and just return that:
SELECT SUM(Fine) As TotalFine
FROM BookReceiveMem
WHERE RecDate = #recDate
Which you could call from code without ever needing a DataTable as follows:
using(var cmd = Con.CreatCommand())
{
cmd.CommandText = "SELECT SUM(Fine) As TotalFine FROM BookReceiveMem WHERE RecDate = #recDate";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#recDate",DateTime.Today);
var result = (int)cmd.ExecuteScalar();
MessageBox.Show("Today Fine Amount is= " + result, "Today Fine Calculation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Note that the above uses a Parameterized Query which is much safer than using string concatenation
However, a more direct answer to your question:
myNum = int.Parse(Dt.Columns[0].ToString());
Here you're getting the Column and trying to turn that to an integer. What you actually meant to do was get the row value (and you dont need to Parse it - it's already an integer!)
myNum = (int)row["Fine"];

How to update the value of an item in a database, using mysql

I am lost on where to go next, I have a database that stores, name, email, uname, password, calories. I want to update the value of the calories column based on what the username is. When a new account is created the value of calories is set to default..
Here is my code I have made a start. I have made a class called database which stores all of my database functions..
The code:
SQLiteDatabase db;
public void
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "update tbltest set calories= "+c.getCalories()+" where uname= "+ c.getUname();
Cursor cursor = db.rawQuery(query , null);;
}
Offer any help on how i can approach this?
Try with this...
public void insertCalories(Intents c)
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("calories", c.getCalories);
String selection = "where uname = ?";
String[] selectionArgs = new String[]{c.getUname()};
int result = db.update(
"tbltest",
values,
selection,
selectionArgs);
}
if result>0, then update is successful.
Put the values in the Contentvalues, you already created.
values.put (columnname, value);
then update the Database with the method update like this:
db.update ("tbltest", values, "WHERE uname = ?", new String []{c.getUname ()});
P.s. You should pass the constructor of Contentvalues the amount of values you want to update

Invalid column name when performing update

I have been trying to update data to database however i met this problem.I tried deleting the table and creating a new table yet the problem still persist.Below are the codes.Any help will be greatly appreciated
public int UpdateNOK(string wardClass, DateTime admissionDT, string nokFName, string nokLName, string nokNRIC, DateTime nokDOB, string nokGender, string nokNationality, string nokRelationship, int nokContactH, int nokContactHP, string nokEmail, string nokAddr1, string nokAddr2, string nokState, int nokZIP, string nokCountry, DateTime dischargeDT, string patientNRIC)
{
StringBuilder sqlStr = new StringBuilder();
int result = 0;
SqlCommand sqlCmd = new SqlCommand();
sqlStr.AppendLine("Update patientAdmission");
sqlStr.AppendLine("SET wardClass = #parawardClass,admissionDT = #paraadmissonDT, nokFName = #parapatientNokFname, nokLName = #parapatientNokLname,nokNRIC = #parapatientNokNRIC, nokDOB = #parapatientNOKDOB, nokGender = #parapatientNokGender, nokNationality = #parapatientNokNationality,");
sqlStr.AppendLine("nokRelationship = #parapatientNokRelationship,nokContactH = #parapatientNokContactH,nokContactHP = #parapatientNokContactHP, nokEmail = #parapatientNokEmail, nokAddr1 = #parapatientNokAddr1,nokAddr2 = #parapatientNokAddr2,nokState = #parapatientNokState, nokZIP = #parapatientNokZIP,");
sqlStr.AppendLine("nokCountry = #parapatientNokCountry, dischargeDT = #paradischargeDateTime");
sqlStr.AppendLine("WHERE patientNRIC = #parapatientNRIC");
try
{
SqlConnection myConn = new SqlConnection(DBConnect);
sqlCmd = new SqlCommand(sqlStr.ToString(), myConn);
sqlCmd.Parameters.AddWithValue("#parawardClass", wardClass);
sqlCmd.Parameters.AddWithValue("#paraadmissonDT", admissionDT);
sqlCmd.Parameters.AddWithValue("#parapatientNokFname", nokFName);
sqlCmd.Parameters.AddWithValue("#parapatientNokLname", nokLName);
sqlCmd.Parameters.AddWithValue("#parapatientNokNRIC", nokNRIC);
sqlCmd.Parameters.AddWithValue("#parapatientNOKDOB", nokDOB);
sqlCmd.Parameters.AddWithValue("#parapatientNokGender", nokGender);
sqlCmd.Parameters.AddWithValue("#parapatientNokNationality", nokNationality);
sqlCmd.Parameters.AddWithValue("#parapatientNokRelationship", nokRelationship);
sqlCmd.Parameters.AddWithValue("#parapatientNokContactH", nokContactH);
sqlCmd.Parameters.AddWithValue("#parapatientNokContactHP", nokContactHP);
sqlCmd.Parameters.AddWithValue("#parapatientNokEmail", nokEmail);
sqlCmd.Parameters.AddWithValue("#parapatientNokAddr1", nokAddr1);
sqlCmd.Parameters.AddWithValue("#parapatientNokAddr2", nokAddr2);
sqlCmd.Parameters.AddWithValue("#parapatientNokState", nokState);
sqlCmd.Parameters.AddWithValue("#parapatientNokZIP", nokZIP);
sqlCmd.Parameters.AddWithValue("#parapatientNokCountry", nokCountry);
sqlCmd.Parameters.AddWithValue("#paradischargeDateTime", dischargeDT);
sqlCmd.Parameters.AddWithValue("#parapatientNRIC", patientNRIC);
myConn.Open();
result = sqlCmd.ExecuteNonQuery();
myConn.Close();
Console.WriteLine(result);
}
catch (Exception ex)
{
logManager log = new logManager();
log.addLog("patientNOKDAO.UpdateNOK", sqlStr.ToString(), ex);
}
return result;
}
}
You should check table definition (sp_help) against your used columns in the table patientAdmission:
wardClass
admissionDT
nokFName
nokLName
nokNRIC
nokDOB
nokGender
nokNationality
nokRelationship
nokContactH
nokContactHP
nokEmail
nokAddr1
nokAddr2
nokState
nokZIP
nokCountry
dischargeDT
patientNRIC
If database default collation is a case-sensitive one, column names above must be exactly as defined in the table (case cannot be different).
One way to find the problem faster is to run SQL profiler and see the exact query against the database. Copy-paste it from there and run it into an Management Studio (SSMS) query file (use BEGIN TRAN .. ROLLBACK to ensure that nothing will actually be changed when you make it work). SSMS will try to indicate the exact column with the problem when clicking on the error.

Android Studio SQLite Column Sum

I have a table with several columns and I'm looking to create a function that will return the sum of all the entries in a particular column.
For debug purposes, I've simply set the return string to "1" to confirm the rest of my code works properly, which it does.
Can anyone help me with the necessary code to sum the column and return the value?
public String TotalServings(){
SQLiteDatabase db = getReadableDatabase();
//From the table "TABLE_PRODUCTS" I want to sum all the entries in the column "COLUMN_SERVINGS"
String Servings = "1";
return Servings;
}
Here's what you need:
//This method returns an int, if u need it string parse it
public Int TotalServings(){
int serving =0;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT SUM(COLUMN_SERVINGS) FROM TABLE_PRODUCTS", null);
if(cursor.moveToFirst()) {
serving = cursor.getInt(0);
}
return serving;
}

how to call sql string from nhibernate

i have the following method, at the moment it's return the whole sql string. How would i execute the following.
using (ITransaction transaction = session.BeginTransaction())
{
string sql =
string.Format(
#"DECLARE #Cost money
SET #Cost = -1
select #Cost = MAX(Cost) from item_costings
where Item_ID = {0}
and {1} >= Qty1 and {1} <= Qty2
RETURN (#Cost)",
itemId, quantity);
string mystring = session
.CreateSQLQuery(sql)
.ToString();
transaction.Commit();
return mystring;
}
// EDIT
here is the final version using criteria
using (ISession session = NHibernateHelper.OpenSession())
{
decimal cost = session
.CreateCriteria(typeof (ItemCosting))
.SetProjection(Projections.Max("Cost"))
.Add(Restrictions.Eq("ItemId", itemId))
.Add(Restrictions.Le("Qty1", quantity))
.Add(Restrictions.Ge("Qty2", quantity))
.UniqueResult<decimal>();
return cost;
}
NHibernate only supports reading results from data readers.
You should create your query string as:
string sql = string.Format(
#"select MAX(Cost) from item_costings
where Item_ID = {0}
and {1} >= Qty1 and {1} <= Qty2",
itemId, quantity);
And then you execute it with:
string mystring = session
.CreateSQLQuery(sql)
.UniqueResult<decimal>()
.ToString();
Anyway, you are not using NHibernate functionality here at all, you're just unnecessarily wrapping raw ADO.NET.
Why not define an object model and query it using Criteria, HQL or Linq?