Roundup in an update sql query - c#

I have a sql column that is set to money, this has four numbers after the decimal point. I am calculating this column in an update query, I would like to roundup this column. example: 2388.6796, should be 2389
Math.Ceiling(0.5);
SqlCommand cmd1 = new SqlCommand("UPDATE Products SET [ThirdPartyRate] = 'Ceiling(" + GridView1.Rows[SelectedIndex].Cells[6].Text.ToString() + "' * [Price]) WHERE [Supplier] like '" + GridView1.Rows[SelectedIndex].Cells[0].Text.ToString() + "' ", con);

Use:
CEILING ( numeric_expression )
In principle you then do: UPDATE TABLE Products SET rounded_val=CEILING(not_rounded_val);
SqlCommand cmd1 = new SqlCommand("UPDATE Products SET [ThirdPartyRate] = CEILING(" +
GridView1.Rows[SelectedIndex].Cells[6].Text.ToString() +
" * [Price]) WHERE [Supplier] like '" +
GridView1.Rows[SelectedIndex].Cells[0].Text.ToString() + "' ", con);

Related

c# fetching database into SQL Server datatable

I have a problem with this code... I don't have the slightest clue for what is happening...
When I run this code in Visual Studio, I get an error saying:
System.InvalidCastException: 'Object cannot be cast from DBNull to other types.'
And here's the code:
conn.Open();
SqlCommand com = new SqlCommand("update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='" + comboBox1.Text + "'", conn);
SqlDataAdapter da = new SqlDataAdapter("Declare #startdate smalldatetime declare #enddate smalldatetime set #startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "') set #enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "') SELECT DATEDIFF(DAY, #startdate+2, #enddate)as timepassedd", conn);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow DR in dt.Rows)
{
int date;
date = Convert.ToInt32(DR["timepassedd"]);
if (date > 0)
{
com = new SqlCommand("DELETE lend WHERE client_name ='"+comboBox1.Text+"'" +
"UPDATE book_list set book_stock = book_stock 1 WHERE book_name ='" + comboBox1.Text + "'",conn);
com.ExecuteNonQuery();
MessageBox.Show("You Returned the book " + date + " Days Late!" +
"please pay the fee to the front desk");
UserPanel u = new UserPanel();
u.Show();
this.Hide();
}
else if (date <= 0)
{
com = new SqlCommand("DELETE lend WHERE client_name ='" + comboBox1.Text + "'" +
"UPDATE book_list set book_stock = book_stock 1 WHERE book_name ='" + comboBox1.Text + "'", conn);
com.ExecuteNonQuery();
MessageBox.Show("You returned the book " + date + " Days Late!" +
"please pay the fee to the front desk");
UserPanel u = new UserPanel();
u.Show();
this.Hide();
}
}
conn.Close();
Thanks in advance
conn.Open();
SqlCommand com = new SqlCommand("update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='" + comboBox1.Text + "'", conn);
SqlDataAdapter da = new SqlDataAdapter("Declare #startdate smalldatetime declare #enddate smalldatetime set #startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "') set #enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "') SELECT DATEDIFF(DAY, #startdate+2, #enddate)as timepassedd", conn);
DataSet ds = new DataSet();
da.Fill(ds);
if(ds.Tables.Count == 1)
{
if(ds.Tables[0].Rows.Count > 0)
{
foreach(DataRow dr in ds.Tables[0].Rows)
{
if(dr.ItemArray.Length > 0)
{
if(dr["timepassedd"] != DBNull.Value)
{
int date;
date = Convert.ToInt32(Dr["timepassedd"]);
if (date > 0)
{
com = new SqlCommand("delete lend where client_name ='" + comboBox1.Text + "'" +
"UPDATE book_list set book_stock = book_stock 1 WHERE book_name ='" + comboBox1.Text + "'", conn);
com.ExecuteNonQuery();
MessageBox.Show("You Returned the book " + date + " Days Late!" +
"please pay the fee to the front desk");
UserPanel u = new UserPanel();
u.Show();
this.Hide();
}
else if (date <= 0)
{
com = new SqlCommand("delete lend where client_name ='" + comboBox1.Text + "'" +
"UPDATE book_list set book_stock = book_stock 1 WHERE book_name ='" + comboBox1.Text + "'", conn);
com.ExecuteNonQuery();
MessageBox.Show("You Returned the book " + date + " Days Late!" +
"please pay the fee to the front desk");
UserPanel u = new UserPanel();
u.Show();
this.Hide();
}
}
}
}
}
}
conn.Close();
You should check for DBNull value, if the column is null-able in the database a DBNull.Value will be returned instead! So you should check this column for such a value before dealing with it
Also, you shouldn't accept values from the user input and directly injecting them into the SQL query! ADO.Net. Has something called Sql Parameters it can be found in the property Parameters in the SqlCommand class. You should use this property to add values from user as parameters to the query
For Example, client name can be added like this:
com.Parameters.Add(new SqlParameter("client_name", comboBox1.Text));
Now you tell the Sql Command that the value is actually presented in the SqlParameters collection like this:
SqlCommand com = new SqlCommand("update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='#client_name'", conn);
Take a look at this question Why do we always prefer using parameters in the SQL statements?
This is a MSDN reference for the Parameters property
Run code below the answer will be obvious :
string sql1 = "update lend set date_back=convert(datetime2, getdate(), 102) where client_name ='" + comboBox1.Text + "'";
Console.WriteLine(sql1);
Console.ReadLine();
SqlCommand com = new SqlCommand(sql1, conn);
string sql2 = "Declare #startdate smalldatetime declare #enddate smalldatetime set #startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "') set #enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "') SELECT DATEDIFF(DAY, #startdate+2, #enddate)as timepassedd"
Console.ReadLine();
SqlDataAdapter da = new SqlDataAdapter(sql2, conn);
set #startdate = (select date_lended from dbo.lend where client_name = '" + comboBox1.Text + "')
set #enddate = (select date_back from dbo.lend where client_name = '" + comboBox1.Text + "')
a) vulnerable to unexpected behaviour if comboBox1.Text was ever to contain ' characters
b) both will result in #startdate or #enddate being NULL if there are no records matching what's selected in the combobox, which then produces a NULL value for '#datepassedd', hence your error when trying to convert to an int.
c) you don't need to query the database twice, you can just do
select DATEDIFF(DAY, date_lended+2, date_back) as timepassedd FROM dbo.lend where client_name = #clientName
(#clientName can then be added a as parameter)
In this case, there will be no rows returned if no records match the name. BTW there was never any need to use a DataTable and iterate through the records, as your query as it is now only ever returns a single row.

Data is not saved in SQL Server table [duplicate]

This question already has answers here:
SQL update statement in C#
(10 answers)
Closed 5 years ago.
enter image description here
I am trying to update data in a SQL Server table. I get a message that data is saved, after a query execution.
But when I check in that table, I find that the data is not saved. Is anything wrong in my query?
I am using SQL Server 2008 and C# for coding.
SqlCommand cmd1 = new SqlCommand("UPDATE Inward_Rpt SET Date='" + date + "',Cashier_Name='" + cashier_name + "',Supplier_Code='" + sup_code + "',Supplier_Name='" + name + "',Payment_Mode ='" + p_method + "',Total_Bill='" + tot_bill + "',Total_Paid='" + tot_paid + "',Previous_Due = '" + total_due + "',Current_Due ='" + c_due + "',Remark ='" + remark + "'WHERE Supplier_Name='" + name + "'", con);
cmd1.ExecuteNonQuery();
MessageBox.Show("Data Saved..");
I think I found your error. Your WHERE clause is using the same name that you are updating the Supplier Name to. Assuming this is a new name, you will never find the record you want to update. The below code is cleaner, not prone to injection issues, and it should work the way you want.
Note that you will have to provide a new variable to cater to the name / sup_name situation.
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = con;
cmd1.CommandText = #"
UPDATE Inward_Rpt
SET Date = #date
, Cashier_Name = #cashier_name
, Supplier_Code = #sup_code
, Supplier_Name = #sup_name
, Payment_Mode = #p_method
, Total_Bill = #tot_bill
, Total_Paid = #tot_paid
, Previous_Due #total_due
, Current_Due = #c_due
, Remark = #remark
WHERE Supplier_Name = #name";
cmd1.Parameters.AddWithValue("#date", date);
cmd1.Parameters.AddWithValue("#cashier_name", cashier_name);
cmd1.Parameters.AddWithValue("#sup_code", sup_code);
cmd1.Parameters.AddWithValue("#sup_name", sup_name);
cmd1.Parameters.AddWithValue("#p_method", p_method);
cmd1.Parameters.AddWithValue("#tot_bill", tot_bill_name);
cmd1.Parameters.AddWithValue("#tot_paid", tot_paid);
cmd1.Parameters.AddWithValue("#total_due", total_due);
cmd1.Parameters.AddWithValue("#c_due", c_due);
cmd1.Parameters.AddWithValue("#remark", remark);
cmd1.Parameters.AddWithValue("#name", name);
cmd1.ExecuteNonQuery();
MessageBox.Show("Data Saved..");
Is the All the Fields are String Datatype in your Database Table? Check the Datatypes Because u give Single Quotes for all Data. If the Table Datatype is Number Remove the Single Quotes.
SqlCommand cmd1 = new SqlCommand("UPDATE Inward_Rpt SET Date='" + date + "',Cashier_Name='" + cashier_name + "',Supplier_Code=" + sup_code + ",Supplier_Name='" + name + "',Payment_Mode ='" + p_method + "',Total_Bill='" + tot_bill + "',Total_Paid='" + tot_paid + "',Previous_Due = '" + total_due + "',Current_Due ='" + c_due + "',Remark ='" + remark + "'WHERE Supplier_Name='" + name + "'", con);

Insert into Order table where customer_id is taken from Customer table where login == session

I don't know how to do this.
When user bought all products i wanna insert it into Orders table, additionally i wanna insert there customer_id from Customer table where user login = Session["id"]. I tried this but it didn't work :/ What should i do?
protected void ConfirmPurchase_Click(object sender, EventArgs e)
{
if (Session["id"] != null)
{
string username;
username = Convert.ToString(Session["id"]);
SqlConnection con = new SqlConnection(#"Data Source=SOME_SQL;Initial Catalog=Shop;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Orders (order_date, paid, transact_status, customer_id) VALUES (GETDATE() ,'" + cost.ToString("c") + "' ,'Przyjęto do bazy', SELECT customer_id FROM Customer WHERE login='" + username + "')", con);
cmd.ExecuteNonQuery();
Response.Redirect("Payment/Payment.aspx");
}
else
{
Response.Redirect("InputPersonalData.aspx");
}
}
You are combining the two flavors of INSERT, INSERT ... VALUES and INSERT ... SELECT; the easiest option in my opinion is to do it through an INSERT ... SELECT:
SqlCommand cmd = new SqlCommand("INSERT INTO Orders (order_date, paid, transact_status, customer_id) SELECT GETDATE() ,'"
+ cost.ToString("c")
+ "' ,'Przyjęto do bazy', customer_id FROM Customer WHERE login='"
+ username + "'", con);
Then, it is a good practice to use parameterized queries, preventing risks like SQL Injection.
You can try by surrounding the user select with "(" and ")"
Instead of
SELECT customer_id FROM Customer WHERE login='" + username + "'
use
( SELECT customer_id FROM Customer WHERE login='" + username + "' )
I think you have to put the subselect into brackets:
SqlCommand cmd = new SqlCommand("INSERT INTO Orders (order_date, paid, transact_status, customer_id) VALUES (GETDATE() ,'" + cost.ToString("c") + "' ,'Przyjęto do bazy', (SELECT customer_id FROM Customer WHERE login='" + username + "'))", con);

C# -SQLCommand -Conversion failed when converting the varchar value 'System.Windows.Forms.Label, Text: 69470570' to data type int

I'm new with programing and need some help here.
Search all over the internet and couldn't find solution.
I have small code, using WinForms application with c#
This is the part of the problematic part:
myConnection.Open();
sqlCommand myCommand16 = new SqlCommand("SELECT Id FROM [dbo].[Units] where unitid='" + textBox1.Text + "'", myConnection);
internalUnitId = myCommand16.ExecuteScalar().ToString();
SqlCommand myCommand15 = new SqlCommand("SELECT TOP 1 REQUESTID FROM [dbo].[ActivationProcStatusMsgd] where unitsid='" + internalUnitId + "' order by id desc", myConnection);
label11.Text = myCommand15.ExecuteScalar().ToString();
// till here all ok.
SqlCommand myCommand25 = new SqlCommand("SELECT TOP 1 [OriginalReqId] FROM [dbo].[ActivationRequestsHistory] where unitsid='" + internalUnitId + "' and originalreqid='" + label11 + "' order by id desc", myConnection);
label18.Text = myCommand25.ExecuteScalar().ToString();
//in This part above i'm getting the exception
In the example below i'm replacing the "label11" with 69470570, and everything is ok.dont understand the different
// SqlCommand myCommand25 = new SqlCommand("SELECT TOP 1 [OriginalReqId] FROM [dbo].[ActivationRequestsHistory] where unitsid='" + internalUnitId + "' and originalreqid='69470570' order by id desc", myConnection);
label18.Text = myCommand25.ExecuteScalar().ToString();
Thanks in advance
Ohad
Problem is in below line :
SqlCommand myCommand25 = new SqlCommand("SELECT TOP 1 [OriginalReqId] FROM [dbo].[ActivationRequestsHistory] where unitsid='" + internalUnitId + "' and originalreqid='" + label11 + "' order by id desc", myConnection);
here you have query formation like :
originalreqid='" + label11 + "'
It should be :
originalreqid='" + label11.Text + "'
Complete line will be :
SqlCommand myCommand25 = new SqlCommand("SELECT TOP 1 [OriginalReqId] FROM [dbo].[ActivationRequestsHistory] where unitsid='" + internalUnitId + "' and originalreqid='" + label11.Text + "' order by id desc", myConnection);
Cause :
label11 is just a object which you are using. You will have to mention its property .Text so as to get proper value.
Instead of label11 in query write label11.Text
you missed to add .Text near Label11 :
SqlCommand myCommand25 = new SqlCommand("SELECT TOP 1 [OriginalReqId] FROM [dbo].[ActivationRequestsHistory] where unitsid='" + internalUnitId + "' and originalreqid='" + label11.Text + "' order by id desc", myConnection);
You should use label11.Text. label11 is name id of the label. It is just an object and cannot be converted to int.

error while executing a ms-access query

I created a query to insert into two ms access tables at a time in c#. I got the exception
{System.Data.OleDb.OleDbException: Characters found after end of SQL
statement. at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult
hr) at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
dbParams, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object&
executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior
behavior, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior
behavior, String method) at
System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at
CompanyDetails.Model.CompanyDetailsModel.setCompanyDetailsToDB(CompanyDetailsDataList
_cmpDetailsList) in E:\Project\PBAttendence\ModifyPrivileage\CompanyDetails\Model\CompanyDetailsModel.cs:line
62}
my sample code is given below please solve my problem. sorry for my bad English.
int companyID = _cmpDetailsList[0].CompanyID;
string companyName = _cmpDetailsList[0].CompanyName;
string contactID = _cmpDetailsList[0].ContactID;
string companyAddress = _cmpDetailsList[0].CompanyAddress;
if (companyID == -1)
{
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity;" + "); ", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
else
{
OleDbCommand upcmd = new OleDbCommand("update CompanyDetails set [CompanyName] = '" + companyName + "',[CompanyAddress] = '" + companyAddress + "',[ContactID] = '" + contactID + "' where [CompanyID] = #cmpID;", conn);
conn.Open();
upcmd.Parameters.AddWithValue("#cmpID", companyID);
upcmd.ExecuteNonQuery();
conn.Close();
}
now i split into two insert command but i got the error {System.Data.OleDb.OleDbException: Syntax error. in query expression 'Select [UserID] from UserDetails;
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
OleDbCommand cmd1 = new OleDbCommand("Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity" + ");", conn);
conn.Open();
cmd1.ExecuteNonQuery();
conn.Close();
The problem is this line of code:
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity;" + "); ", conn);
You have two insert statements in the same OleDbCommand. Try to move this into two different steps:
Insert into CompanyDetails table
Insert into UserCompanyDetails table
Hope this helps you
First of all , it would have been easier with the raw sql command then your code generating the sql.
You might consider making a stored procedure since your command is getting kinda complex
If i'm correct , what you are currently trying to do is :
Insert into table1(x,y,z) values a,b,c;
Insert into table2(x,y) values select * from table3; , ##identity
The second sql command is invalid in both syntax and logic, your ##identity won't be static since you're inserting new records during your command.
My recommendation would be to do something like this :
Insert into table1(x,y,z) values a,b,c;
declare #table1Id int = ##identity
Insert into table2(x,y) select colA, #table1Id from table3;
You cannot have ; in queries in Access. See http://office.microsoft.com/en-us/access-help/HV080760224.aspx You will have to do the two inserts separately as suggested by #juanreyesv
You will have to do 3 queries,
Do the insert using your sql: "Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "')
Get the ##identity using
Select ##identity and store it in a variable say idnt
Use the identity value obtained in 2. to do the third insert:
"Insert into UserCompanyDetails([UserID],[CompanyID])
Select UserID, " + idnt.ToString() + " from UserDetails"
Refer to http://msdn.microsoft.com/en-us/library/ks9f57t0%28VS.71%29.aspx

Categories

Resources