how to update a column( in SQL) by adding a specific amount to the old one? - asp.net

thats the code...
SQL = string.Format("Insert into Orders (AID,ODate) Values({0},'{1}')", AID, odate);
Dbase.ChangeTable(SQL, "Database1.mdb");
SQL = "Select MAX(OID) as MAXOID from Orders";
dt = Dbase.SelectFromTable(SQL, "Database1.mdb");
OID = dt.Rows[0][0].ToString();
string PID = Session["PID"].ToString();
SQL = string.Format("Insert into ListedProducts (OID,PID,PCat,cnt) Values({0},{1},'{2}',{3})", OID, PID, "B", cnt);
Dbase.ChangeTable(SQL, "Database1.mdb");
Label6.Text = "Your Product has been added to your basket , go to your basket to commit your order.";
// HEREEEEEEE///
SQL = String.Format("Update [Orders] SET [price]=[price]+{0} Where [OID]={1}", int.Parse(cnt) * pr, OID);
//SQL = "UPDATE [Orders] SET [price]=" + int.Parse(cnt) * pr + " WHERE OID=" + OID;
////////////////
Dbase.ChangeTable(SQL, "Database1.mdb");
so it should work and it doesnt show me an error but it doesnt add anything to the database but if i wont be adding it would update.
my database consists of OID,ODate,price,AID..

Run the SQL Commands manually and ensure your logic is correct... it's possible that your UPDATE is running but not doing anything since your WHERE isn't finding the OID you're passing in.

Related

sqlite.swift how to do subquery

I'm attempting a query to get the latest N messages in a particular conversation from a table of messages. I think this is the correct sql:
select * from
(select * from messages where convoId = to order by timestamp DESC limit 10)
order by timestamp ASC;
I have attempted this in sqlite.swift:
static let table = Table("messages")
let query = (table.filter(convoId == to).order(timestamp.desc).limit(10)).select(table[*]).order(timestamp.asc)
which is not working once the amount of messages goes past the limit. Is there any way to see what sql is produced by the sqlite.swift query? Any suggestions?
EDIT: I have also attempted the raw SQL query but now I'm not sure how to extract the result. I feel like this should be a last resort:
let toQuoted = "'" + to + "'"
let subQueryStr: String = [
"(SELECT * FROM",
MessageDataHelper.TABLE_NAME,
"WHERE",
MessageDataHelper.CONVO_ID, "=", toQuoted, "ORDER BY", MessageDataHelper.TIMESTAMP, "DESC LIMIT", String(5), ")"
].joined(separator: " ")
let queryStr: String = [
"SELECT * FROM",
subQueryStr,
["ORDER BY", MessageDataHelper.TIMESTAMP, "ASC;"].joined(separator: " ")
].joined(separator: "\n")
let stmt = try db.prepare(queryStr)
for row in stmt {
// ? how can this be used to create model structure
for (index, name) in stmt.columnNames.enumerate() {
print ("\(name)=\(row[index]!)")
}
}
row[index] is of type Binding, so I'm unsure how to retrieve the value there. Help please!
Thanks
Okay, so looks like sub query might be too complex to express in sqllite.swift. I ended up going with the raw sql query. You can retrieve the result by casting the binding as mentioned here:
Getting results from arbitrary SQL statements with correct binding in SQLite.swift

Create new sql entry with one value being MAX(Column)+1 gives Invalid use of group function

I want to manually create a ID field where I do MAX + 1, and I want to do it in one QUERY so I am certain 2 entries cant get the same field.
using (MySqlConnection dbConn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ProjektConStr"].ConnectionString))
{
dbConn.Open();
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO Submission (CaseId , SubjectId, CenterId, EmployeeName, Reason, Description, Explanation, Date, Done, ChiefLevel) VALUES (MAX(CaseId)+1, #subject_id, #center_id, #employee_name, #reason, #description, #explanation, #date, #done, #chief)", dbConn))
{
cmd.Parameters.AddWithValue("date", submission.Date);
cmd.Parameters.AddWithValue("subject_id", submission.SubjectId);
cmd.Parameters.AddWithValue("center_id", submission.CenterId);
cmd.Parameters.AddWithValue("employee_name", submission.EmployeeName);
cmd.Parameters.AddWithValue("reason", submission.Reason);
cmd.Parameters.AddWithValue("description", submission.Description);
cmd.Parameters.AddWithValue("explanation", submission.Explanation);
cmd.Parameters.AddWithValue("done", false);
cmd.Parameters.AddWithValue("chief", false);
cmd.ExecuteNonQuery();
}
}
Use subquery to select max and insert a value
INSERT INTO Submission (CaseId , SubjectId, CenterId, EmployeeName, Reason, Description, Explanation, Date, Done, ChiefLevel) VALUES (
(1 + coalesce((SELECT max(CaseId) FROM Submission), 0))
, #subject_id, #center_id, #employee_name, #reason, #description, #explanation, #date, #done, #chief)
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO Submission
(CaseId , SubjectId, CenterId, EmployeeName, Reason, Description, Explanation,
Date, Done, ChiefLevel)
VALUES ((select MAX(CaseId)+1 from YourTable),
#subject_id, #center_id, #employee_name, #reason, #description, #explanation,
#date, #done, #chief)", dbConn))
You cannot do this in a single query, Either you have to fetch the MAX_id and then increment that, and insert or You can make the table as autoincrement, Here you dont have to include the id in the insert query.

creating a sufficient query search sql

I am writing a query to allow a user to search on what they provide keywords in asp.net, C# and mssql:
string projectPart = null;
string categoryPart = null;
string descriptionPart = null;
if (this.Textbox_ProjectNr.Text.Trim().Length > 0)
projectPart = " AND Number='" + this.Textbox_ProjectNr.Text.Trim() + "' ";
if (this.Textbox_Category.Text.Trim().Length > 0)
categoryPart = " AND Category LIKE '%" + this.Textbox_Category.Text.Trim() + "%' ";
if (this.Textbox_pDescription.Text.Trim().Length > 0)
descriptionPart = " AND ProductDescription LIKE '%" + this.Textbox_pDescription.Text.Trim() + "%' ";
string query = "SELECT * from Project = p.ID " + projectPart + descriptionPart + categoryPart;
I dont know whether this query is sufficient for a traditional query search. Because I see there are some bottlenecks of this search:
if the user does not type anything, it returns all of the data => For this I only do the query when one of the fields are filled.
if the user provides some keywords "P" for each field, the result will be millions of data.
I dont know how to improve the search query basically. any suggestions are appreciated.
Thanks in adavance.
The most important improvement is to protect you code against SQL injection attacks.
You should not concatenate the raw input in the SQL string. If someone searches for the following text for example:
Bwah ha ha'; DROP DATABASE northwind; PRINT'
This will be added to your query to produce
SELECT *
FROM mytable
WHERE category LIKE '%Bwah ha ha'; DROP DATABASE northwind; PRINT'%'
This is a valid SQL command and will happily execute and drop your database (or do anything else the attacker wants)
For more information see SQL Injection and Santitizng Inputs.
You must make this query injection proof! Do not concatenate user entered values, but use parameters, like this:
SqlCommand cmd = new SqlCommand(#"
SELECT * from Project
WHERE
( Number = #Number OR #Number IS NULL ) AND
( Category LIKE #Category OR #Category IS NULL ) AND
( ProductDescription LIKE #ProductDescription OR #ProductDescription IS NULL )", conn);
if(!String.IsNullOrEmpty(this.Textbox_ProjectNr.Text.Trim()))
cmd.Parameters.AddWithValue("#Number", this.Textbox_ProjectNr.Text.Trim());
if(!String.IsNullOrEmpty(this.Textbox_Category.Text.Trim()))
cmd.Parameters.AddWithValue("#Category", this.Textbox_Category.Text.Trim());
if(!String.IsNullOrEmpty(this.Textbox_pDescription.Text.Trim()))
cmd.Parameters.AddWithValue("#ProductDescription", this.Textbox_pDescription.Text.Trim());
Also, you can add some client validation on user entered values. For instance, ask for more than three (?) characaters before running that query.
<asp:TextBox ID="Textbox_ProjectNr" runat="server" />
<asp:RegularExpressionValidator ID="Textbox_ProjectNr_Validator" runat="server"
ControlToValidate="Textbox_ProjectNr"
ErrorMessage="Minimum length is 3"
ValidationExpression=".{3,}" />
First of all, you must protect yourself from sql injections. You haven't specified what connection to the database you are using but most libraries allow adding the parameters in a different field, so they are sanitized automatically.
Secondly, you can (and should) limit the results count using the "LIMIT" (for mysql) or "TOP X" Like so:
Select * from TableName LIMIT 100 or Select TOP 100 * from TableName

DataGrid view in asp.net is not displaying data

I want to dispaly column in datagrid view using custom query statement
but i want to send value to parametrized data in query
how can i do this ?
my code is below
select
c.customer_id,
c.customer_first_name,
c.customer_last_name,
c.customer_address,
c.account_number,
c.account_type,
a.account_balance,
t.transfer_amount_balance,
t.samebank_transfer_id,
t.account_number_same_bank,
t.transferdatetime
FROM customer_details c join account_details a on c.account_number = a.account_number
join transactions_details t on a.account_number = t.account_number where
c.customer_id = 'cus0010' and a.account_number = 'acc0010'
this above code working properly in sql server 2005
but the code below which is modified as per asp.net page for grid view is not showing
any result
select
c.customer_id,
c.customer_first_name,
c.customer_last_name,
c.customer_address,
c.account_number,
c.account_type,
a.account_balance,
t.transfer_amount_balance,
t.samebank_transfer_id,
t.account_number_same_bank,
t.transferdatetime
FROM customer_details c join account_details a on c.account_number = a.account_number
join transactions_details t on a.account_number = t.account_number where
c.customer_id = 'Label1.Text' and a.account_number = 'Label2.Text'
the above is placed in my custom sql query section it
is triggered by button click in my asp page or any other
idea to display it will be welcomed
Use:
string.Format("c.customer_id = '{0}' and a.account_number = '{1}'", Label1.Text, Label2.Text);
Consider this query:
string query = "insert into TestTable (Column1, Column2) values (#p1, #p2)";
p1 & p2 are parameters, in order to set the value for the parameters you need to use:
queryParameters[0] = new SqlCeParameter("p1", SqlDbType.NVarChar);
queryParameters[0].Value = Label1.Text;
queryParameters[1] = new SqlCeParameter("p2", SqlDbType.NVarChar);
queryParameters[1].Value = Label2.Text;
SqlCeCommand command = new SqlCeCommand(query);
command.Parameters.AddRange(queryParameters);
When the wizard is generating the query you need to use place holders/parameters for customer_ID and account_number and set their values by using parameters.
Edit:
In order to make the wizard create a parameter to use in the query, add a ? in the filter column in the query builder wizard.
Well, I may misunderstand, but...you are not actually sending the string 'Label1.Text' I guess? You should send the value of the textbox, something like this (if you are building the SQL as a string?):
...[SQL]... + "c.customer_id = '"+ Label1.Text + "'" ...[rest of the SQL]

Strange result with

When i run this as my first commend i get an exception an error near "last_insert_rowid". This is referring to the last last_insert_rowid();. If i set the curser to the line command.CommandText = and run it again it is fine.
What gives? The last_insert_rowid seems to be working properly why doesnt the last_insert_rowid after the 2nd insert work.
I tried moving last_insert_rowid() to after the execute and i still get an error. What gives?
using (var trans = connection.BeginTransaction())
{
command.CommandText =
"INSERT INTO link_list(link, status, hash_type, hash_id) " +
"VALUES(#link, #status, #hash_type, #hash_id);" +
"INSERT INTO active_dl(linkId, orderNo) " +
"VALUES(last_insert_rowid(), (SELECT COUNT(*) FROM active_dl)); last_insert_rowid();";
command.Parameters.Add("#link", System.Data.DbType.String).Value = link;
command.Parameters.Add("#status", System.Data.DbType.Int32).Value = SiteBase.Status.none;
command.Parameters.Add("#hash_type", System.Data.DbType.Int32).Value = 0;
command.Parameters.Add("#hash_id", System.Data.DbType.Int32).Value = 0;
int rowid = command.ExecuteNonQuery();
trans.Commit();
}
Why is the last last_insert_rowid() there? After the second insert you call last_insert_rowid with no select or anything to identify what you want to do with it.
You would have to put a select in front of it to retrieve the value wouldn't you?
You're trying to execute 2 sql commands in the one statement. You'll need to split the 2 statements up into 2 calls and return the inserted id from the first statement.
An alternative suggestion is a stored procedure but I don't think sqlite supports these.

Resources