MySQL update +- amount - c#

I got this update thing i cant figure out. The save button seems to be working, its updating the table. I cant seem to figure out the SaveToStock method. It throws me this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''90' at line 1
I tried putting a breakpoint, got this. Break data
Save button
protected void saveButton_Click(object sender, EventArgs e)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySQLParser parser = new MySQLParser(connection);
int nonsoldamount = 0;
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
nonsoldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'", "amount"));
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
nonsoldamount = nonsoldamount + oldamount;
}
if (nonsoldamount < Convert.ToInt32(TextBoxAmount.Text))
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are only " + nonsoldamount + " in stock with the selected attributes</span>"));
return;
}
}
else
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are 0 in stock with the selected attributes</span>"));
return;
}
string sql_query = "";
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
sql_query = "UPDATE dpf_sale SET orderNo = ?orderNo, fk_operatorID = ?operator, status = ?status, amount = ?amount, geometry = ?geometry, length = ?length, CPSI = ?CPSI " +
"WHERE dpfSaleID = ?IDdpfSale";
}
else
{
sql_query = "INSERT INTO dpf_sale (orderNo, fk_operatorID, amount, geometry, length, CPSI, status) " +
"VALUES (?orderNo, ?operator, ?amount, ?geometry, ?length, ?CPSI, ?status)";
}
MySqlCommand myCommand = new MySqlCommand(sql_query, connection);
myCommand.Parameters.AddWithValue("?IDdpfSale", IDdpfSale);
myCommand.Parameters.AddWithValue("?orderNo", TextBoxOrderNo.Text);
myCommand.Parameters.AddWithValue("?operator", DropDownListOperator.SelectedValue);
myCommand.Parameters.AddWithValue("?geometry", DropDownListGeometry.SelectedValue);
myCommand.Parameters.AddWithValue("?length", DropDownListLength.SelectedValue.Replace(',', '.'));
myCommand.Parameters.AddWithValue("?status", DropDownListStatus.SelectedValue);
myCommand.Parameters.AddWithValue("?CPSI", DropDownListCPSI.SelectedValue);
myCommand.Parameters.AddWithValue("?amount", TextBoxAmount.Text);
myCommand.ExecuteNonQuery();
saveToStock();
}
editing = false;
IDdpfSale = 0;
Response.Redirect("dpf_sale.aspx");
}
Stock Change
private void saveToStock()
{
connection = new MySqlConnection(connectionString);
parser = new MySQLParser(connection);
connection.Open();
string sql_stock = "";
string sql_log = "";
int newsaleID;
if (editing == true)
{
sql_stock = "UPDATE dpf_stock SET amount = amount + " + oldamount + " - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
sql_log = "UPDATE dpf_stock_log SET amount = " + TextBoxAmount.Text + " WHERE sale = 1 and id = " + IDdpfSale;
}
else
{
newsaleID = Convert.ToInt32(parser.readSelectCommand("SELECT MAX(dpfSaleID) id FROM dpf_sale", "id"));
sql_log = "INSERT INTO dpf_stock_log (id, assembly, sale, amount) VALUES (" + newsaleID + ", 0, 1, " + TextBoxAmount.Text + ")";
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
sql_stock = "UPDATE dpf_stock SET amount = amount - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
}
else
{
return;
}
}
MySqlCommand myCommand1 = new MySqlCommand(sql_stock, connection);
myCommand1.ExecuteNonQuery();
MySqlCommand myCommand2 = new MySqlCommand(sql_log, connection);
myCommand2.ExecuteNonQuery();
connection.Close();
}

Related

the data types varchar and varchar are incompatible in the subtraction operator c# web service

Currently i use five layers and in my Business layer I've one method for then call him into my Web Service but I can't make a subtraction
public void ActualizarStock(ConsultaStock consultaStock, int cantidad_salida)
{
this.configurarConexion();
this.Conec.CadenaSQL = "UPDATE Consulta_stock "
+ " SET cantidad = '" + consultaStock.Cantidad.ToString() + "' - '"
+ cantidad_salida.ToString()
+ "' WHERE sku = '" + consultaStock.Sku + "';";
this.Conec.EsSelect = true;
this.Conec.conectar();
}
Like this:
this.Conec.CadenaSQL = "UPDATE Consulta_stock "
+ " SET cantidad = " + consultaStock.Cantidad.ToString() + " - "
+ cantidad_salida.ToString()
+ " WHERE sku = '" + consultaStock.Sku + "';";
or why not:
this.Conec.CadenaSQL = "UPDATE Consulta_stock "
+ " SET cantidad = " + (consultaStock.Cantidad - cantidad_salida).ToString()
+ " WHERE sku = '" + consultaStock.Sku + "';";
The ' character in SQL is used a a string delimiter, you could do de calculation before the query or just get rid of the '.
For example:
public void ActualizarStock(ConsultaStock consultaStock, int cantidad_salida)
{
int nuevoStock = consultaStock.Cantidad - cantidad_salida;
this.configurarConexion();
this.Conec.CadenaSQL = "UPDATE Consulta_stock SET cantidad = " + nuevoStock.ToString() + " WHERE sku = '" + consultaStock.Sku + "';";
this.Conec.EsSelect = true;
this.Conec.conectar();
}

Why is my Ajax data not sending through to my SQL Server

I am trying to get my data from a web page to a server without requiring a page refresh. The js brings in the data; however, it (the data) does not reach my db, I am new to ajax and not sure if I am doing this correctly
JS:
function insert() {
let batchid = document.getElementById("batchID").value;
let batchname = document.getElementById("batchName").value;
let totenum = document.getElementById("toteNum").value;
let flower = document.getElementById("flowers").value;
let trim = document.getElementById("trim").value;
let wastemat = document.getElementById("wasteMaterial").value;
let empint = document.getElementById("empInital").value;
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "insert.cshtml?bid=" + batchid + "&bn" + batchname + "&tn" + totenum + "&fl" + flower + "&tr=" + trim + "&wm" + wastemat + "&ei" + empint , false);
xmlhttp.send(null);
alert(" Record inserted successfully");
}
C#:
SqlConnection con = new SqlConnection(Server);
string batchID, batchName, toteNum, flowers, trim, wasteMaterial, empInital;
public void OnGet()
{
batchID = Request.Query["bid"].ToString();
batchName = Request.Query["bn"].ToString();
toteNum = Request.Query["tn"].ToString();
flowers = Request.Query["fl"].ToString();
trim = Request.Query["tr"].ToString();
wasteMaterial = Request.Query["wm"].ToString();
empInital = Request.Query["ei"].ToString();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO HarvestedCannabis VALUES ('" + batchID.ToString() + "', '" + batchName.ToString() + "', " +
"'" + toteNum.ToString() + "', '" + flowers.ToString() + "', " +
"'" + trim.ToString() + "', '" + wasteMaterial.ToString() + "', " +
"'" + empInital.ToString() + "')";
cmd.ExecuteNonQuery();
con.Close();
The data is not being added to my db and I am not sure what I'm missing

Data type mismatch in criteria expression in WPF Application

Please help me out in this error.
I am using access database in C# and developing WPF application. Here, I am writing updating query and i got the below error :-
"Data type mismatch in criteria expression".
Here, Retail and Cut_Off both are checkbox. I added it later.When I added checkbox later it gives me this error.
I stored checkbox value like below :-
cmentity.Retail = chkRetailIndividualBidder.IsChecked.Value.ToString();
cmentity.Cut_Off = chkCutOff.IsChecked.Value.ToString();
Below code wrote in Clientmasterrepository.cs file
public int UpdateForAllClientInfo(ClientMaster cmentity)
{
string strQuery = "UPDATE ClientMaster SET " +
"Applied_Quantity = '" + cmentity.Applied_Quantity + "', " +
"Amount = '" + cmentity.Amount + "', " +
"Cheque_in_Favour = '" + cmentity.Cheque_in_Favour + "', " +
"Retail_Individual_Bidder = '" + cmentity.Retail + "', " +
"Cut_Off = '" + cmentity.Cut_Off + "' " +
"WHERE IsDeleted = " + 0;
return oConnectionClass.ExecuteNonQuery(strQuery);
}
below code wrote in connection.cs file:-
public int ExecuteNonQuery(string strQuery)
{
OleDbConnection oleDbConnection = new OleDbConnection(strConnectionString);
OleDbCommand oleDbCommand = new OleDbCommand(strQuery, oleDbConnection);
oleDbCommand.CommandText = strQuery;
oleDbCommand.CommandType = CommandType.Text;
oleDbConnection.Open();
oleDbCommand.ExecuteNonQuery();
oleDbConnection.Close();
return 1;
}

Tweetinvi Unable to get tweets constantly 24/7 with not getting stuck

I'm trying to find out why tweetinvi streaming library is getting stuck when it's getting too much tweets from the followers, that I add with the function AddFollow(). In this function I'm putting 600 followers using a list that I create. Each of these tweets that I receive on my application go directly to a database but in at a uncertain time the application just stops bringing tweets and it doesn't show any error or exception in the debugging mode. The program it's in C# and I'm using visual studio 2012
Here is my code:
public void getTweets()
{
string[] sports = new string[] { "NFL" };
long[] list1 = critter_connex(sports);
int cont = 0;
DateTime pastDate = DateTime.MinValue;
string tweetType = "";
int id = 0;
using (var webClient = new WebClient())
{
webClient.Proxy = WebRequest.DefaultWebProxy;
webClient.Credentials = System.Net.CredentialCache.DefaultCredentials; ;
webClient.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
webClient.Headers["User-Agent"] = "MOZILLA/5.0 (WINDOWS NT 6.1; WOW64) APPLEWEBKIT/537.1 (KHTML, LIKE GECKO) CHROME/21.0.1180.75 SAFARI/537.1";
//using app key NECESITO VER TWEETS3
var credentials = TwitterCredentials.CreateCredentials("XXXXX", "XXXXX", "XXXXX", "XXXXX");
try
{
TwitterCredentials.ExecuteOperationWithCredentials(credentials, () =>
{
cont++;
var filteredStream = Stream.CreateFilteredStream();
for (int i = 0; i < list1.Length; i++)
{
filteredStream.AddFollow(list1[i]);
}
try
{
filteredStream.MatchingTweetReceived += (sender, arg) =>
{
try
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
MySqlCommand command = new MySqlCommand();
MySqlDataReader reader;
command.Connection = conn;
command.CommandText = "SELECT sportName, specTeam FROM twitter_userids where userId = " + arg.Tweet.Creator.Id.ToString() + "";
command.Prepare();
reader = command.ExecuteReader();
try
{
if (reader.Read())
{
tweet.setSport(reader.GetString(0));
tweet.setTeam(reader.GetString(1));
}
}
finally
{
reader.Close();
conn.Close();
}
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
Console.WriteLine(ex.Message);
}
try
{
cont++;
if (cont == 10)
{
filteredStream.StopStream();
DateTime date = DateTime.Now;
getTweets();
}
if (tweetType == "Tweet")
{
if (pastDate > arg.Tweet.CreatedAt)
{
filteredStream.StopStream();
DateTime date = DateTime.Now;
getTweets();
}
}
if (arg.Tweet.IsRetweet)
{
tweet.setUser_name(arg.Tweet.RetweetedTweet.Creator.ScreenName);
tweet.setText(arg.Tweet.RetweetedTweet.Text);
tweet.setPublish_date(arg.Tweet.RetweetedTweet.CreatedAt);
tweet.setRetweet_date(arg.Tweet.CreatedAt);
tweetType = "Retweet";
tweet.setState("Retweet");
tweet_text = tweet.getText();
Console.WriteLine(tweet.getUser_name());
Console.WriteLine(tweet.getText());
string rt_final_date = tweet.getPublish_date().ToString("yyyy-MM-dd HH:mm:ss");
string rt_date = tweet.getRetweet_date().ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(rt_final_date);
Console.WriteLine(rt_date);
Console.WriteLine(tweet.getSport());
Console.WriteLine(tweet.getTeam());
Console.WriteLine("Retweet");
Console.WriteLine("\n");
if (tweet_text.IndexOf("http://") > -1)
{
int index = tweet_text.IndexOf("http://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
else
if (tweet_text.IndexOf("https://") > -1)
{
int index = tweet_text.IndexOf("https://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
MySqlCommand insert_rt = conn.CreateCommand();
if (tweet.getLink() != "")
{
insert_rt.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_link, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM (SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + tweet.getLink().Replace("'", "") + "', '" + rt_final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "' LIMIT 50) LIMIT 1";
}
else
{
insert_rt.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM (SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + rt_final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "' LIMIT 50) LIMIT 1";
}
conn.Open();
id = insert_rt.ExecuteNonQuery();
conn.Close();
tweet.setLink("");
}
else
{
tweet.setUser_name(arg.Tweet.Creator.ScreenName);
tweet.setText(arg.Tweet.Text);
pastDate = arg.Tweet.CreatedAt;
tweet.setPublish_date(arg.Tweet.CreatedAt);
tweetType = "Tweet";
tweet.setState("Tweet");
tweet_text = tweet.getText();
Console.WriteLine(tweet.getUser_name());
Console.WriteLine(tweet.getText());
string final_date = tweet.getPublish_date().ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(final_date);
Console.WriteLine(tweet.getSport());
Console.WriteLine(tweet.getTeam());
Console.WriteLine(tweet.getState());
Console.WriteLine("\n");
if (tweet_text.IndexOf("http://") > -1)
{
int index = tweet_text.IndexOf("http://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
else
if (tweet_text.IndexOf("https://") > -1)
{
int index = tweet_text.IndexOf("https://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
MySqlCommand insert_t = conn.CreateCommand();
if (tweet.getLink() != "")
{
insert_t.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_link, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM ( SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + tweet.getLink().Replace("'", "") + "', '" + final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "') LIMIT 1";
}
else
{
insert_t.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM ( SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "') LIMIT 1";
}
conn.Open();
id = insert_t.ExecuteNonQuery();
conn.Close();
tweet.setLink("");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
};
filteredStream.StartStreamMatchingAllConditions();
}
catch (Exception ex)
{
Console.WriteLine(ex);
getTweets();
}
tweet_text = "";
getTweets();
filteredStream.StartStreamMatchingAllConditions();
});
getTweets();
}
catch (Exception ex)
{
getTweets();
Console.WriteLine(ex);
}
getTweets();
}
}
Thanks.
Have you tried to register to the StreamStopped event and check that everything is working correcly?
filteredStream.StreamStopped += (sender, args) =>
{
Console.WriteLine(args.DisconnectMessage.Reason);
if (args.Exception != null)
{
Console.WriteLine(args.Exception);
}
};

C# Syntax error (missing operator) in query expression

I receive this error on cmd.ExecuteNonQuery()... I think I am wrong on cmd.CommandText...
Syntax error (missing operator) in query expression 'Nr_Crt='1' and Varsta '3' and KG '2' and Specie 'Iepure' and Risc'Nu' and Tip1 'Diurn' and Tip2 'Carnivor''.
private void button2_Click_1(object sender, EventArgs e)
{
if (txtNr_Crt.Text != " " & txtVarsta.Text != " " & txtKG.Text != " " & txtSpecie.Text != " " & txtRisc.Text != " " & txtTip1.Text != " " & txtTip1.Text != " " & txtTip2.Text != "")
{
cn.Open();
cmd.CommandText = "DELETE from Animale Where Nr_Crt='" + txtNr_Crt.Text + "' and Varsta '" + txtVarsta.Text + "' and KG '" + txtKG.Text + "' and Specie '" + txtSpecie.Text + "' and Risc'" + txtRisc.Text + "' and Tip1 '" + txtTip1.Text + "' and Tip2 '" + txtTip2.Text + "'";
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
txtNr_Crt.Text = "";
txtVarsta.Text = "";
txtKG.Text = "";
txtSpecie.Text = "";
txtSex.Text = "";
txtRisc.Text = "";
txtTip1.Text = "";
txtTip2.Text = "";
}
}
You code is vulnerable to SQL injection, i'd fix that.
The issue is that you are missing the = from each of your subsequent and's:
cn.Open();
cmd.Parameters.AddWithValue("#Nr_Crt", txtNr_Crt.Text);
cmd.Parameters.AddWithValue("#Varsta", txtVarsta.Text);
cmd.Parameters.AddWithValue("#KG", txtKG.Text);
cmd.Parameters.AddWithValue("#Specie", txtSpecie.Text);
cmd.Parameters.AddWithValue("#Risc", txtRisc.Text);
cmd.Parameters.AddWithValue("#Tip1", txtTip1.Text);
cmd.Parameters.AddWithValue("#Tip2", txtTip2.Text);
cmd.CommandText = "DELETE from Animale Where Nr_Crt= #Nr_Crt and Varsta = #Varsta and KG = #KG and Specie = #Specie and Risc = #Risc and Tip1 = #Tip1 and Tip2 = #Tip2";
cmd.ExecuteNonQuery();
cn.Close();
This should fix it (and the SQL injection risk)
Your query is wrong. You are missing = when comparing the columns
cmd.CommandText = "DELETE from Animale Where Nr_Crt='" + txtNr_Crt.Text + "' and Varsta='" + txtVarsta.Text + "' and KG='" + txtKG.Text + "' and Specie='" + txtSpecie.Text + "' and Risc='" + txtRisc.Text + "' and Tip1='" + txtTip1.Text + "' and Tip2='" + txtTip2.Text + "'";
foreach(Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
ctrl.text="";
}
}
For cleaning all textbox at once :) you can create a Method that performs it when you need it

Categories

Resources