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
Related
edit: I'm aware of SQL Injection.
First of all, I know my coding methods are terrible but thats what I can for now, extremely beginner on c#.
I'm trying to read data from SQL server and show them on Textboxes.
User going to write (and choose from cmbbox) some data on;
cmbIl.Text, cmbIlce.Text, cmbMahalle.Text, txtAda.Text, txtPafta.Text
and press the button for search.
If that data correspond to the values in sql database (true), some other data will be taken and shown at
txtTapuKodu.Text, txtPafta.Text, txtTapuAlani.Text, txtNitelik.Text,
rtxtImarDurumu.Text
But the code below gives that error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'
private void btnSorgula_Click(object sender, EventArgs e)
{
string source = #"Data Source=YAGIZ-PC;Initial Catalog=imar_sorgu;Integrated Security=True";
SqlConnection con = new SqlConnection(source);
con.Open();
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "', ilce = '" + cmbIlce.Text + "', mahalle = '" + cmbMahalle.Text + "', ada = '" + txtAda.Text + "', parsel = '" + txtParsel.Text + "'";
/* string sqlSelectQuery2 = "SELECT * FROM tablo_arsa WHERE ilce ='" + cmbIlce.Text + "'";
string sqlSelectQuery3 = "SELECT * FROM tablo_arsa WHERE mahalle ='" + cmbMahalle.Text + "'";
string sqlSelectQuery4 = "SELECT * FROM tablo_arsa WHERE ada = " + txtAda.Text;
string sqlSelectQuery5 = "SELECT * FROM tablo_arsa WHERE parsel = " + txtParsel.Text; */
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
txtTapuKodu.Text = (dr["tapu_kodu"].ToString());
txtPafta.Text = (dr["pafta"].ToString());
txtTapuAlani.Text = (dr["tapu_alani"].ToString());
txtNitelik.Text = (dr["nitelik"].ToString());
rtxtImarDurumu.Text = (dr["imar_durumu"].ToString());
MessageBox.Show("İstek başarıyla okundu.");
}
else
{
MessageBox.Show("Okuma başarısız.");
}
con.Close();
}
The problem is that your where clause contains commas between the predicates. use AND instead.
change:
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "', ilce = '" + cmbIlce.Text + "', mahalle = '" + cmbMahalle.Text + "', ada = '" + txtAda.Text + "', parsel = '" + txtParsel.Text + "'";
to:
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "' AND ilce = '" + cmbIlce.Text + "' AND mahalle = '" + cmbMahalle.Text + "' AND ada = '" + txtAda.Text + "' AND parsel = '" + txtParsel.Text + "'";
However, PLEASE read about SQL INJECTION. It is a very bad security issue and this is a perfect example.
I've been trying to update in a DataGridView and it keeps returning this
No value given for one or more required parameters
Here's my code
private void btnAlterar_Click(object sender, EventArgs e)
{
try
{
string strincon = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\flavi\Desktop\Pet&Shop.2\PetShop\TelaAbertura\bin\Debug\DatabasePS.mdb;Persist Security Info=True";
OleDbConnection con = new OleDbConnection(strincon);
con.Open();
String comando = "UPDATE Funcionario SET Nome= '" + txtNome.Text + "' , Login= '" + txtLogin.Text + "' , Senha= '" + txtSenha.Text + "', Email= '" + txtEmail.Text + "' , Cargo= '" + txtCargo.Text + "' WHERE Codigo =" + codigo;
OleDbCommand cmd = new OleDbCommand(comando, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Dados Alterados Com Sucesso!");
txtCargo.Clear();
txtEmail.Clear();
txtLogin.Clear();
txtNome.Clear();
txtSenha.Clear();
con.Close();
}
catch (Exception erro)
{
MessageBox.Show(erro.Message);
}
}
You need to add brackets on field names because may be some field name is keyword on Access. Change your query as follow:
String comando = "UPDATE [Funcionario] SET [Nome]= '" + txtNome.Text + "' , [Login]= '" + txtLogin.Text + "' , [Senha]= '" + txtSenha.Text + "', [Email]= '" + txtEmail.Text + "' , [Cargo]= '" + txtCargo.Text + "' WHERE [Codigo] =" + codigo;
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();
}
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;
}
So Visual Studio tells me that my quotes are not right in the update statement. I feel it might be something more than that. I feel I am close but I don't see where I am going wrong in this sql statement. The point of the webpage is to update the database that is all for this step. Can someone help me out.
Here is my code.
P.S. - I did an insert statement similar to this but the string idString part all the way to the softwareReportRecord.Close(); was beneath the update statement and it worked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
reportDateText.Text = DateTime.Today.ToShortDateString();
//code page 429
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
bugReportForm.Visible = false;
regMessage.Visible = true;
string typeOS = oSListbox.SelectedValue;
string reportDate = reportDateText.Text;
string hardware = hardwareText.Text;
string occurrence = occurrenceRadioButtonList.SelectedValue;
string shortDescription = shortDescriptionText.Text;
string longDescription = longDescriptionText.Text;
string actionsTaken = actionsTakenText.Text;
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("BugsReport");
}
catch (SqlException exception)
{
if (exception.Number == 911)
{
SqlCommand sqlCommand = new SqlCommand("CREATE DATABASE BugsReport", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text = "<p>Successfully created the database.</p>";
dbConnection.ChangeDatabase("BugsReport");
}
else
Response.Write("<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>");
}
finally
{
regMessage.Text += "<p>Successfully selected the database.</p>";
}
try
{
string SQLString = "SELECT * FROM softwareLog";
SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection);
SqlDataReader idRecords = checkIDTable.ExecuteReader();
idRecords.Close();
}
catch (SqlException exception)
{
if (exception.Number == 208)
{
SqlCommand sqlCommand = new SqlCommand("CREATE TABLE softwareLog (reportID SMALLINT IDENTITY(100,1) PRIMARY KEY, typeOS VARCHAR(25), reportDate DATE, hardware VARCHAR(50), occurrence VARCHAR(15), shortDescription VARCHAR(100), longDescription VARCHAR(500), actionsTaken VARCHAR(25))", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text += "<p>Successfully created the table.</p>";
}
else
regMessage.Text += "<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>";
}
finally
{
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "' "
+ "occurrence='" + occurrence + "' "
+ "shortDescription='" + shortDescription + "' "
+ "longDescription='" + longDescription + "' "
+ "actionsTaken='" + actionsTaken + "' "
+ "WHERE reportID=" + reportID + ";";
SqlCommand sqlCommand = new SqlCommand(editRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
dbConnection.Close();
}
}
}
}
finally
{
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS + "', '"
+ reportDate + "', '"
+ hardware + "', '"
+ occurrence + "', '"
+ shortDescription + "', '"
+ longDescription + "', '"
+ actionsTaken + "')";
SqlCommand sqlCommand = new SqlCommand(addRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
regMessage.Text += "<p>Sorry for your inconvience. We will be working on your problem ASAP. For reference your ID is </p>" + reportID;
dbConnection.Close();
You are missing too many "," in Update.
EDIT You have single quote inside string. You need to escape those quotes also:
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS.Replace("'", "''") + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware.Replace("'", "''") + "',"
+ "occurrence='" + occurrence.Replace("'", "''") + "',"
+ "shortDescription='" + shortDescription.Replace("'", "''") + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken.Replace("'", "''") + "'"
+ "WHERE reportID= " + reportID ;
In insert you don't need quote for reportID:
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS.Replace("'", "''") + "', '"
+ reportDate + "', '"
+ hardware.Replace("'", "''") + "', '"
+ occurrence.Replace("'", "''") + "', '"
+ shortDescription.Replace("'", "''") + "', '"
+ longDescription.Replace("'", "''") + "', '"
+ actionsTaken.Replace("'", "''") + "')";
Chances are the data being passed to the query be terminating the string early. For many reasons (including this one, but also SQL injection), you should be using parameters instead of concatenation.
Try like this,
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "',"
+ "occurrence='" + occurrence + "',"
+ "shortDescription='" + shortDescription + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken + "'"
+ "WHERE reportID=" + reportID + "";
Can you please Add your Insert Statement too.
Remarks : It will better to use Parametrized SqlCommand or Store
Procedure to perform this type of operation.
If you supply value with ' to any field then, it will not work. Also check value you supply for ReportId.
In this example you should be using parameters as a precaution against SQL injection as others have mentioned.
But for other strings I suggest you look into string.Format() rather than concatenating everything. Would make that string so much easier to read.