updating values - sql

public void ModificaNomeUtente(int slipno , int basicprice , int premium, int totalamountpaid, int weight , int totalamountbasic , int totalamountpremium , int yeildestimates , int farmercode)
{
// Creo la stringa di Connessione al DataBase
SqlConnection sqlConn = new SqlConnection(#"Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True");
// Prova
try
{
// Creo la query che andrà a modificare il nome utente
string sqlQuery = "UPDATE cottonpurchse SET slipno = '" + slipno + "' + basic price = '" + basicprice + "' + premium = '" + premium + "' + totalamountpaid = '" + totalamountpaid + "' + weight = '" + weight + "' + totalamountbasic = '" + totalamountbasic + "' + totalamountpremium = '" + totalamountpremium + "' + yeildestimated = '" + yeildestimates + "' = WHERE farmercode = '" + FarmerCode + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn);
// Apro la connessione con il DataBase Login.sdf
sqlConn.Open();
// Eseguo l'istruzione sql
cmd.ExecuteNonQuery();
// Chiudo la connessione con il DataBase Login.sdf
sqlConn.Close();
// Se la query ha avuto esito positivo imposto la variabile result a true
result = true;
}
// In caso di eccezzione
catch (Exception ex)
{
// Visualizzo il messaggio con la relativa eccezzione verificatasi
MessageBox.Show(ex.Message);
// Chiudo la connessione con il DataBase Login.sdf
sqlConn.Close();
// la query ha avuto esito negativo imposto la variabile result a false
result = false;
}
finally
{
// Chiudo la connessione con il DataBase Login.sdf
sqlConn.Close();
}
}
this doesnt work its not updating could it be cause my values are set to null ?

That statement parses to something like;
UPDATE cottonpurchse
SET slipno = '???' + basic price = '???' + premium = '???' + totalamountpaid = '???' + weight = '???' + totalamountbasic = '???' + totalamountpremium = '???' + yeildestimated = '???' = WHERE farmercode = '???'
There is an = before the WHERE which is illegal, did you mean , instead of + ?
UPDATE cottonpurchse
SET slipno = '???' , basic price = '???' , premium = '???' , totalamountpaid = '???' , weight = '???' , totalamountbasic = '???' , totalamountpremium = '???' , yeildestimated = '???' WHERE farmercode = '???'

UPDATE: everyone's comments are valid. Your SQL is full of errors: extra spaces, extra +, and extra =. You are confusing yourself trying to build up a string that way...
That said, your SQL query string should be this:
string sqlQuery = "UPDATE cottonpurchse SET slipno=" + slipno + ", basicprice=" + basicprice + ", premium=" + premium + ", totalamountpaid=" + totalamountpaid + ", weight=" + weight + ", totalamountbasic=" + totalamountbasic + ", totalamountpremium=" + totalamountpremium + ", yeildestimated=" + yeildestimates + " WHERE farmercode=" + FarmerCode;
It is confusing becuase you are building a string. The best (and safest) way to do what you are trying to do is use SQL parameters. See: c# Sqlcommand error (specifically the answer that shows "Parameters.Add")

Related

Dapper query, combining attributes to use with pagination

I have that query that shows all my Boats, but I would just like to show the active boats.
public Pagination<Boats> GetAll(string name , int pageSize, int pageNumber)
{
var cn = Db.Database.Connection;
var sql = #"SELECT * FROM Boats" +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%')" +
"ORDER BY [Name ] " +
"OFFSET " + pageSize * (pageNumber - 1) + " ROWS " +
"FETCH NEXT " + pageSize + " ROWS ONLY " +
" " +
"SELECT COUNT(Id) FROM Boats" +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%')";
var multi = cn.QueryMultiple(sql, new { Name = name });
var boats= multi.Read<Boats >();
var total = multi.Read<int>().FirstOrDefault();
var paginationList= new Pagination<Boats>()
{
List = boats,
Count = total
};
return paginationList;
}
I have the active and excluded attributes in the table, so I tried to show only the boats that were active, but with this query, it keeps returning all records from the boat table, like frist one
var sql = #"SELECT * FROM Boats " +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%' AND Active=1 AND Excluded=0)" +
"ORDER BY [Name] " +
"OFFSET " + pageSize * (pageNumber - 1) + " ROWS " +
"FETCH NEXT " + pageSize + " ROWS ONLY " +
" " +
"SELECT COUNT(Id) FROM Boats " +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%' AND Active=1 AND Excluded=0)";
Any Ideas how can I combine the Name attribute with the Active and Excluded attributes?
Remove it from the parenthesis:
"WHERE (#Name IS NULL OR Name LIKE #Name + '%') AND Active=1 AND Excluded=0"

ORA 00905 missing keyword in Select statement

try {
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
st3 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select insp_no,ro_code, inspectiondate from keroseneheader where ro_code='" + cust_code + "' and status='NO' and inspectedby='" + em.ro_code + "'");
if (rs.next())
{
session.setAttribute("insp_no", rs.getString("insp_no"));
out.print(rs.getString("insp_no") + "#" + rs.getString("inspectiondate"));
}
else
{
rs3 = st3.executeQuery("select * from keroseneheader where ro_code='" + cust_code + "' and inspectiondate>to_date('" + inspectdate + "','dd-mm-yyyy') and inspectedby='" + em.ro_code + "'");
if (!rs3.next())
{
String query2 = "insert into keroseneheader(insp_no,ro_code,inspectiondate,status,inspectedby) values((select nvl(max(INSP_NO)+1,1) from keroseneheader),'" + cust_code + "',"
+ "to_date('" + inspectdate + "','dd-mm-yyyy'),'NO','" + em.ro_code + "')";
boolean i = DbConn.insertupdatedata(query2, false);
if (i) {
st1 = con.createStatement();
rs1 = st1.executeQuery("select insp_no,to_char(inspectiondate,'dd-mm-yyyy') inspectiondate from keroseneheader where ro_code=" + cust_code + " and status='NO' and inspectedby='" + em.ro_code + "'");
if (rs1.next()) {
session.setAttribute("insp_no", rs1.getString("insp_no"));
out.print(rs1.getString("insp_no") + "#" + rs.getString("inspectiondate"));
}
}
}
else {
out.print("Invalid Date");
}
}
Change this line
st1.executeQuery("select insp_no,to_char(inspectiondate,'dd-mm-yyyy') inspectiondate from keroseneheader
To this
st1.executeQuery("select insp_no,to_char(inspectiondate,'dd-mm-yyyy') as 'inspectiondate' from keroseneheader

How to read the values in SQL

I am tying to read the values in SQl.
I am creating one purchase order If suppose any body has updated the price for the inventory then I am first checking that price is available or not.
If that price is not available then I am First Inserting that price into the datbase & then map new price with the inventory.
I have already achieved this functionality but I have wrote five inline query for this now i need to
change the code & replace with the single stored procedure. & how I can write the logic into the SQL
Here is my code with the explanation
//Checking that Buying Price Is Exist or not
//string CheckingIBM = "select * from RS_Inventory_Buying_Master where buying_price ='" + UpdatedPrice + "'";
//cm.TableConnect(CheckingIBM);
//If Buying Price is Exist then Update PIIM table with new buying_product_id
if (cmIS_Price_Exist.rs.Read())
{
//If Buying Price is Exist then Update PIIM table with new buying_product_id
common cm1 = new common();
string BuyingProductId = cmIS_Price_Exist.rs["buying_product_id"].ToString();
string UpdatePIIM = "update RS_Purchase_Invoice_Info_Master set buying_product_id = '" + BuyingProductId + "', qty = '" + UpdatedQuantity + "',tax_id ='" + TaxDetails + "',picreated = 1 where purchase_order_no = '" + PO + "' and product_id = '" + ProductId + "'";
cm1.TableInsert(UpdatePIIM);
cm1.con.Close();
}
//If Buying Price does not Exist then first Insert the price & then Update the other tables
else
{
//If Price is not exist then firsrt insert the price
common cm2 = new common();
string InsertBuyingPrice = "insert into RS_Inventory_Buying_Master (buying_price,latest) values ('" + UpdatedPrice + "','0')";
cm2.TableInsert(InsertBuyingPrice);
cm2.con.Close();
//After inserting the price find the buying product Id of that price
common cm3 = new common();
string FindingUpdatedPrice = "select * from RS_Inventory_Buying_Master where buying_price ='" + UpdatedPrice + "'";
cm3.TableConnect(FindingUpdatedPrice);
//Now finallly after finding the buying price id by using the inserted Price. Now update the buying product id of PIIM
if (cm3.rs.Read())
{
string BuyingProductId = cm3.rs["buying_product_id"].ToString();
//Now finallly after finding the buying price id. Now update the buying product id of PIIM
common cm4 = new common();
string UpdatePIIM = "update RS_Purchase_Invoice_Info_Master set buying_product_id = '" + BuyingProductId + "', qty = '" + UpdatedQuantity + "',tax_id ='" + TaxDetails + "',picreated = 1 where purchase_order_no = '" + PO + "' and product_id = '" + ProductId + "'";
cm4.TableInsert(UpdatePIIM);
cm4.con.Close();
}
cm3.con.Close();
}
Any suggesion will be appreciated.
declare #BuyingProductId varchar(50)
set #BuyingProductId = (select isnull(buying_product_id, '') from RS_Inventory_Buying_Master where buying_price = #UpdatedPrice)
if(#BuyingProductId <> '')
begin
--your update query
update RS_Purchase_Invoice_Info_Master set buying_product_id = #BuyingProductId ,
qty = #UpdatedQuantity ,tax_id = #TaxDetails ,picreated = 1
where purchase_order_no = #PO
and product_id = #ProductId ;
end
else
begin
--your insert query
insert into RS_Inventory_Buying_Master (buying_price,latest)
values (#UpdatedPrice,'0')
set #BuyingProductId = (SELECT ##IDENTITY)
update RS_Purchase_Invoice_Info_Master set buying_product_id = #BuyingProductId ,
qty = #UpdatedQuantity ,tax_id = #TaxDetails ,picreated = 1
where purchase_order_no = #PO
and product_id = #ProductId ;
end
Check with this query. Please make sure to create new sp and provide all the value like #UpdatedQuantity etc.

Getting Error: Column does not exist

When adding rows to a table I am getting Error: column does not exist and I am not sure why. I know the table does and it is fairly straight forward. Here is what I have to add and here is what the table looks like. Any help would be great and let me know if you have any questions. Thanks!
Whatever value I have in emailField it is giving me the error that emailfield column does not exist
final String addemployee = "insert into employee values ('" + name_field.getText() + "', '" + usersSuper.getText() + "', '" + true + "' , md5('" + passwordField.getText() + "') , " + emailField.getText() + ");";
Here is the table
CREATE TABLE employee
(
name text NOT NULL,
manageremail text,
isadmin boolean NOT NULL,
userpassword text NOT NULL,
email text NOT NULL,
CONSTRAINT "user_Email" PRIMARY KEY (email)
)
Try
final String addemployee = "insert into employee values ('" + name_field.getText() + "', '" + usersSuper.getText() + "', '" + true + "' , md5('" + passwordField.getText() + "') , '" + emailField.getText() + "');";
You've missed quotes around emailField.getText()? it should be '" + emailField.getText() + "'

SQL UPDATE doesn't work with foreign languages (Arabic)

the UPDATE gives ???? if the updater field was written in Arabic and this is my query:
UPDATE students
SET first_name = 'الاسم' , last_name = 'الاسم الاخير' ,
father_name = 'الاسم الاخير' , mother_name = '',
birth_date = '1/1/1990 12:00:00 AM' , education_level = '' ,
address = '' , notes = ''
WHERE student_id = 33
And here is the result of the update:
student_id first_name last_name mother_name father_name birth_date
33 ????? ????? ?????? ??????????? 1990-01-01
//the answer is great and thank you people, another question is that I am using this UPDATE syntax in my C# program
command.CommandText = "UPDATE students SET " +
"first_name = " + "'" + first_name + "'" + " , last_name = " + "'" + last_name + "'" +
" , father_name = " + "'" + father_name + "'" + " , mother_name = " +
"'" + mother_name + "'" + ", birth_date = " + "'" + birth_date + "'" +
" , education_level = " + "'" + education_level + "'" +
" , address = " + "'" + address + "'" + " , notes = " + "'" + notes + "'" +
" WHERE student_id = " + id ;
//how to use the character N
You have forgotten the N prefix before your string literals which is required so they will be treated as nvarchar rather than varchar
SET first_name = N'الاسم' etc.
without that the text is coerced into whatever characters the code page of your default collation can deal with.
Create the database with this collation Arabic_CI_AS, you won't need to put N before the Arabic characters.