i'm still new in c# programing ,is any one can help me to solve this error coming when i try to add a data in database but error comes after this line command.ExecuteNonQuery();
private void button1_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\aberto\Documents\esimar_db.accdb;Persist Security Info=False;";
string cmdstr = "insert into employee(employee_name, location,connection,depanse,caisse)values(#employee_name,#location,#connection,#depanse,#caisse)";
OleDbConnection connect = new OleDbConnection(constr);
OleDbCommand command = new OleDbCommand(cmdstr, connect);
connect.Open();
command.Parameters.AddWithValue("#employee_name", textBox1.Text);
command.Parameters.AddWithValue("#location", comboBox1.Text);
command.Parameters.AddWithValue("#connection", textBox2.Text);
command.Parameters.AddWithValue("#depanse", textBox3.Text);
command.Parameters.AddWithValue("#printing", textBox4.Text);
command.Parameters.AddWithValue("#caisse", textBox5.Text);
command.ExecuteNonQuery();
MessageBox.Show( "Record saved successfully");
connect.Close();
}
CONNECTION is reserved word in Access SQL so you have to enclose it in square brackets if it is to be used as a column (or table) name:
string cmdstr =
"insert into employee(employee_name, location, [connection], depanse, caisse) values (#employee_name, #location, #connection, #depanse, #caisse)";
Also, be aware that your CommandText only has five (5) parameters in it, but you have six (6) Parameters.AddWithValue statements. OleDb ignores parameter names and only pays attention to the order in which the parameters are declared, so only the first five (5) of those statements will have any effect.
Related
I've been trying to insert data into a MS Access database and I can't see what is wrong with my insert statement. I checked all the values and they should be the same, I even tried a really simple statement with static values but it doesn't work anyways.
I've followed the syntax to the letter but I still keep getting an INSERT INTO error when I get to the cmd.ExecuteNonQuery() command.
string str = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\B8328\source\repos\KaihatsuEnshuu\KaihatsuEnshuu\OI21Database1.accdb";
OleDbConnection con = new OleDbConnection(str);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO order (orderEmpno, orderCustomerId) VALUES (#orderEmpno, #orderCustomerId)";
cmd.Parameters.AddWithValue("#orderEmpno", comboBox1.SelectedValue);
cmd.Parameters.AddWithValue("#orderCustomerId", comboBox2.SelectedValue);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("An order has been started");
I am trying to add data into a database. When I run code in the save button method, the above error pops up.
try
{
string constr = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Noah\Desktop\vs13\Project\JW_Accounting_Appliction\JW_Accounting_App\myDatabase.mdf;Integrated Security=True";
SqlConnection conn = new SqlConnection(constr); //connects to regstration DB//
conn.Open(); //to open connection to DB
String insertQuery = "insert into AccountReceipt(TNo.,[Date], [WorldWide], [Local], [sumWW_Local]) values (#TNo., #Date, #WorldWide, #Local, #sumWW_Local)"; // inserts into table and declares data as variables//
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#TNo.", textBox1.Text);
com.Parameters.AddWithValue("#Date", pickerDate.Text);
com.Parameters.AddWithValue("#WorldWide", txtWorldWide.Text);
com.Parameters.AddWithValue("#Local", txtLocal.Text);
com.Parameters.AddWithValue("#sumWW_Local", txtTotal.Text);
com.ExecuteNonQuery();
MessageBox.Show("Thank you, Your registration has been successfull!");
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
The usage of parameterization is appreciated, But you have to care about naming conventions as well. Here the issue is with the column name TNo. please enclose then inside a [] ie.,
"insert into AccountReceipt([TNo.] .. // rest of codce)
Anyway TNo. would not be a good name for a column, try to follow some good naming conventions
Don't use No. both in column name and in paramater.
insert into AccountReceipt([TNo.],[Date], [WorldWide], [Local], [sumWW_Local]) values (#TNo, #Date, #WorldWide, #Local, #sumWW_Local)
com.Parameters.AddWithValue("#TNo", textBox1.Text);
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection("Data Source=SALE7\\SALE7;Initial Catalog=YOUTUBE;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand("INSERT INTO tblContacts VALUES (#FIRSTNAME,#LASTNAME)", cs);
da.InsertCommand.Parameters.Add("#FIRSTNAME", SqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("#LASTNAME", SqlDbType.VarChar).Value = textBox2.Text;
cs.Open();
da.InsertCommand.ExecuteNonQuery(); // Error occurs here
cs.Close();
}
The exception detail:
Column name or number of supplied values does not match table
definition.
The problem is you may have more than two columns in your table but you have missed to include
da.InsertCommand = new SqlCommand("INSERT INTO tblContacts(FIRSTNAME,LASTNAME) VALUES (#FIRSTNAME,#LASTNAME)", cs);
The exception is telling you what is wrong:
Your table does not have two columns (my guess: it has more).
So, if you just have an ID element with autoincrement, you may change your Command to
da.InsertCommand = new SqlCommand("INSERT INTO tblContacts (firstname,lastname) VALUES (#FIRSTNAME,#LASTNAME)", cs);
you should use insert query like this
INSERT INTO tblContacts(first_name_column_name, last_name_column_name) VALUES (#FIRSTNAME,#LASTNAME)
this error raised because you have more than 2 columns in your table and database couldn't know which columns you try to fill
You might have more the more than two column as you specify.
use query like:
Insert INTO tblContacts(firstname,lastname) VALUES (#firstname,#lastname)
So im having problem gettin some data in to the database.. Im really stuck, im quite new to c# and have not learned all keywords yet, im not getting any errors just some nothing adds to my database.
textBox2.Text = myPWD;
MySqlConnection conn = new MySqlConnection("test")
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES ('values = #val')";
MySqlCommand data = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
SelectCommand.Parameters.AddWithValue("#val", this.textBox2.Text);
conn.Closed()
Manipulate the concatenation of value in passing of parameters. Don't do it inside sql statement.
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES (#val)";
// other codes
SelectCommand.Parameters.AddWithValue("#val", "values = " + this.textBox2.Text);
the reason why the parameter is not working is because it was surrounded by single quotes. Parameters are identifiers and not string literals.
The next problem is you did not call ExecuteNonQuery() which will execute the command.
Before closing the connection, call ExecuteNonQuery()
// other codes
data.ExecuteNonQuery();
conn.Close();
You should Google around and you will receive lots of content
You need to run ExecuteNonQuery
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into st (ID,Name) values ('11','seed');", con);
cmd.ExecuteNonQuery();
cmd.Close();
I basically want to store some values into the database.
I keep getting the error "Number of query values and destination fields are not the same."
pointing towards the dr = cmd.ExecuteReader();
Can someone please help me? :)
I am kinda new to the whole thing and don't really know whats happening.
Bellow is the code am using.
public partial class Registeration_experiment : System.Web.UI.Page
{
static OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
OleDbDataAdapter ada = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string str = "insert into Registeration_Test (Name1, address, emailaddress)" +
"values (?, ?, ?)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", TextBox2.Text);
cmd.Parameters.AddWithValue("#p4", TextBox4.Text);
cmd.ExecuteNonQuery();
}
}
Thank you :)
You are writing to the database, not reading from it.
No sense to use ExecuteReader, you need a ExecuteNonQuery for that
EDIT
Seeing now the structure of the table. It is composed of 5 fields.
In this case, you have two choices. Provide the name of the fields that you want to update in the insert statement or add a parameter for every field
First choice, you don't give the name of the fields
(pass a parameter for every field except the ID because I suppose it is an AutoIncrement field, meaning that the database manages itself the value for that field)
// No name provided for fields, need to pass a parameter for each field
string str = "insert into Registeration_Test values (?, ?, ?, ?)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", Textbox1.Text);
cmd.Parameters.AddWithValue("#p2", Textbox2.Text);
cmd.Parameters.AddWithValue("#p3", Textbox3.Text);
cmd.Parameters.AddWithValue("#p4", Textbox4.Text);
cmd.ExecuteNonQuery();
(Note, the TextBox1... etc are the names you have provided in you example above, I don't know the exact content of these textboxes where the user types the data to insert in the database, nor I don't know if they really exists in your page/form)
Second choice, you declare the fields that should be updated in the database
// Just three named fields updated
string str = "insert into Registeration_Test (Name1, address, emailaddress)" +
"values (?, ?, ?)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", Textbox1.Text);
cmd.Parameters.AddWithValue("#p2", Textbox2.Text);
cmd.Parameters.AddWithValue("#p4", Textbox4.Text);
cmd.ExecuteNonQuery();
Please note also that I have changed your sql command to not use string concatenation.
It is a very bad practice that leads to numerous problem. The worst one is Sql Injection, not to mention problems with string parsing when text contains single quotes or other problematic characters
A parameter placeholder is represented (in OleDb) by the ? in the command text. This placeholder will be replaced by the actual value added in the parameter collection of the OleDbCommand (in the exact order in which the placeholders appears). Using Parameters (Parametrized query) allows the framework to examine the values passed and take appropriate actions if these values are invalid.
EDIT
The problem with connection arises from a previous command that has left the connection open. This is another bad practice. Every connection should be: created, opened, used, closed. The pseudocode to follow is this
// Create the connection
using(OleDbConnection con = GetOleDbConnection())
{
con.Open();
... // use the connection with insert/delete/update/select commands
}
// Exiting from the using block close and destroy (dispose) the connection