String strSql = "insert into BaseData (Item," + dataGridView1.Columns[3].Name + "," + dataGridView1.Columns[4].Name + ") values ('" + row.Cells[0].Value + "','" + row.Cells[3].Value + "','" + row.Cells[4].Value + "')";
objCmd = new OleDbCommand(strSql, lConn);
objCmd.ExecuteNonQuery();
strSql = "select id from BaseData where Item = '" + row.Cells[0].Value + "' and " + dataGridView1.Columns[1].Name + " = '" + row.Cells[3].Value + "' And " + dataGridView1.Columns[2].Name + " = '" + row.Cells[4].Value + "'";
OleDbCommand command = new OleDbCommand(strSql, lConn);
OleDbDataReader reader = command.ExecuteReader();
String id = "";
while (reader.Read())
{
id = reader.GetString(0);
}
reader.Close();
strSql = "insert into tranjaction (Base_id,quentity,price,other) values ('" + id + "' , ' " + row.Cells[2].Value + "','" + row.Cells[1].Value + "')";
objCmd = new OleDbCommand(strSql, lConn);
objCmd.ExecuteNonQuery();
When I run this, Microsoft Visual Studio Error occur on Line 10. (ExecuteReader)
The Error is here.
An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: No value given for one or more required
parameters.
How could I fix this error?.
Either your field names are wrong (quentity?) or it's because you have unbalanced fields to parameters. You are inserting into 4 fields, but you are only supplying 3 values. Use parameters instead, it would make your life easier.
Try changing it to this:
strSql = "insert into tranjaction (Base_id,quentity,price,other) values (#id , #quentity, #price, #other)";
using (OleDbCommand cmd = new OleDbCommand(sqlSql, IConn)) {
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#quentity", row.Cells[2].Value);
cmd.Parameters.AddWithValue("#price", row.Cells[1].Value);
cmd.Parameters.AddWithValue("#other", other); // <- missing
cmd.ExecuteNonQuery();
}
When I've received this error in the past it has always been because of a simple typo. Like the others have mentioned it looks like you spelled "quantity" wrong which could be part of the problem.
In this line
strSql = "insert into tranjaction (Base_id,quentity,price,other) values ('" + id + "' , ' " + row.Cells[2].Value + "','" + row.Cells[1].Value + "')";
you are inserting 4 values (Base_id,quentity,price,other), but you are only inserting 3 values (id, row.Cells[2].Value, row.Cells[1].Value). Giving a value for other should fix the problem.
Another thing that would cause this error, which is probably your situation, is if you've spelled one of the column names incorrectly. And since you are using column names from your datagridview, and some of your written column names seem mis-spelled, you should double check the spelling in your query strings.
Related
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);
Can someone please help me figure out why I am getting 'System.Web.UI.WebControls.TextBox' in MySQL database instead of actual values being entered in the text field. The code I am using is below ..
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
string queryStr;
string connString=System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnectionString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO seework.userdata (First_Name, Middle_Name, Last_Name, Email_Address, Phone_Number, Username, Password)" + "VALUES('" + firstnameTextBox + "','" + middlenameTextBox + "','" + lastnameTextBox + "','" + emailaddressTextBox + "','" + phonenoTextBox + "','" + usernameTextBox + "','" + passwordTextBox + "')";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
I have tried all I could but still no luck. Any help would be really appreciated.
Thanks in Advance!
You are passing the TextBox itself to the database using the query. You need to pass the text instead. For this you can use .Text property of the TextBox control. Which gives you the Text/Content inside the Textbox Control. And one more advise for you. Use Parameterized queries instead for cuch queries to avoid Sql Injection.
For example:
queryStr = "INSERT INTO seework.userdata (First_Name, Middle_Name)VALUES(#fName,#mName)";
SqlCommand cmd = new SqlCommand(queryStr);
cmd.Parameters.Add("#fName",SqlDbType.VarChar).Value=firstnameTextBox.Text ;
cmd.Parameters.Add("#mName",SqlDbType.VarChar).Value=middlenameTextBox.Text;
// Build your command like this
// Execute the command then
you should use .Text after the name of TEXTBOX.
For Example :-
string insert = "insert into table_Name (Name, Contact, Email) values ('" + txtname.Text + "', '" + txtcontact.Text + "', '" + txtemail.Text + "')";
I'm getting the error:
Data type mismatch in criteria expression
When using this code. And using Access database.
OleDbConnection bab = new OleDbConnection();
bab.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\sdega\OneDrive\school\Werknemersdata.accdb;Persist Security Info=False;";
bab.Open();
try
{
OleDbCommand kaas = new OleDbCommand();
kaas.Connection = bab;
kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values ('" + txtNaam.Text + "', '" + txtAdress.Text + "', '" + txtpostcode1.Text + " " +txtpostcode2.Text + "', '" + txtwoonplaats.Text + "', '" + txtsalaris.Text + "') ";
kaas.ExecuteNonQuery(); // this is where it goes wrong
txtStatus.BackColor = Color.Green;
MessageBox.Show("data saved");
bab.Close();
}
catch (Exception ghakbal)
{
MessageBox.Show("Error" + ghakbal);
}
You missed one ' after '" + txtpostcode1.Text + " and one before " +txtpostcode2.Text + "' and also one , between them. It should be like this:
'" + txtpostcode1.Text + "' , '" +txtpostcode2.Text + "',
Also I strongly recommend that you always use parameterized queries to avoid SQL Injection. Like this:
kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values (?, ? ,.....");
kaas.Parameters.AddWithValue("Naam", txtNaam.Text);
kaas.Parameters.AddWithValue("Adres", txtAdress.Text);
//And other parameters...
Also It would be better to specify the type directly and use the Value property. Read more here.
I am getting an error while inserting data into a database.
The error is:
"Number of query values and destination fields are not the same".
Insert code:
OleDbConnection vconn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Mutyyba\\Documents\\Database1.accdb");
vconn.Open();
string name = textBox1.Text;
string address = textBox3.Text;
int rollno = Convert.ToInt32(textBox2.Text);
string vquery = "insert into Table1 values(#vname,#vrollno,#vaddress)";
OleDbCommand vcomm = new OleDbCommand(vquery, vconn);
vcomm.Parameters.AddWithValue("#vname", name);
vcomm.Parameters.AddWithValue("#vrollno", rollno);
vcomm.Parameters.AddWithValue("#vaddress", address);
vcomm.ExecuteNonQuery();
MessageBox.Show("your record has been recorded sucessfully!");
vconn.Close();
What am I doing wrong?
I think you just missed some single quotes . I see you have enclosed all the parameters with a starting and end single quotes . See this
One more thing , as you are passing lot of parameter prepare a SqlCommand Object for Parameters.
See msdn for more details.
Do something like this :
SqlCommand comm = new SqlCommand("INSERT INTO table VALUES (#txtsno, #txtdesg, #txtbasic)", connection);
comm.Parameters.AddWithValue("#txtsno", txtsno.Text.Trim());
comm.Parameters.AddWithValue("#txtsno", txtdesg.Text.Trim());
comm.Parameters.AddWithValue("#txtsno", txtbasic.Text.Trim());
This would be more clearer and would not be prone of SQL Injection.
Try to use parameters to build the command
// Create the InsertCommand.
command = new OleDbCommand(
"INSERT INTO Customers (CustomerID, CompanyName) " +
"VALUES (?, ?)", connection);
// add parameters like below
command.Parameters.Add(
"CustomerID", OleDbType.Char, 5, "CustomerID");
command.Parameters.Add(
"CompanyName", OleDbType.VarChar, 40, "CompanyName");
You need to specify the column names in your SQL, or the value sequence should be the exact same (number and order) with the default schema of the table
OleDbCommand cmd = new OleDbCommand("insert into real (name, symbol, date, red, redby, redsell, sbintrabuy, sbtr1, sbtr2, sbtr3, sbintersell, sbtr1, sbtr2, sbtr3, rstl, green) values('" + Name + "','" + Symbol + "','" + Date + "','" + Red + "','" + RedBuy + "','" + RedSell + "','" + SBIntraBuy + "','" + SBTR1 + "','" + SBTR2 + "','" + SBTR3 + "','" + SBIntraSell + "','" + SBTR1 + "','" + SBTR2 + "','" + SBTR3 + "','" + RSTL + "','" + Green + "');", con);
Replace the bold columns with correct names, it's recommended that to specify the column names explictly.
The string values should be around with single quota
Normally, you should write sql like this:
cmd.Parameters.Add("var", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["var"].Value = 'somevalue';
In your sql should be like: "insert into real(column1) values(#var)".
====
I updated the answer as above, hope it can solve your problem.
insert into Main values (28494,1,False,'Buto-asma Sirop' , 'Buto-asma Sirop', 3.99 , 'Syrup', 'ispani', ' ', ' ',0, '1',4988 )
solves this problem
this is the code
public static void ChangeTable(string strSql, string FileName)
{
OleDbConnection c = MakeConnection(FileName);
OleDbCommand comm = new OleDbCommand();
comm.CommandText = strSql;
comm.Connection = c;
comm.ExecuteNonQuery();
c.Close();
}
strSql = "Insert into h3rot(name,lastname,tlfon,nyad,email,brodcuts)" +
" VALUES(
'
" +
TextBox1.Text +
"','" +
TextBox2.Text +
"'," +
phone +
"," +
pel +
",'" +
TextBox5.Text +
"','" +
DropDownList1.Text + "
')";
1) your code is SCREAMING out "sql injection" so you should REALLY be doing something to sanitize all of those textboxes. And you should at least be using parameter markers instead of just appending strings together.
2) you've probably exceeded the size of one of the columns in your database. without more information about what was in the textboxes or the schema of the database, there's not much else to say.
try DropDownList1.SelectedValue