Store values in the Access Database - c#

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

Related

Accessing Listbox Results View in C#

Hi there guys i am sure this is quite easy i am just completely new to C#.
So I can read the SQL database and bring back results but I cant figure out how to read the returning result which should then be inserted into the Database.
Any idea how I can read the Result View because i can see the value i want in there. Value for this example is 'AS'
SqlConnection con = new SqlConnection("Data Source=###;Initial Catalog=######;Persist Security Info=True;User ID=##;Password=#######");
SqlCommand cmd = new SqlCommand("Select ISOCode from Countries Where CountryName like '" + CTRYLST.SelectedItem + "%'", con);
con.Open();
CTRYLST.Items.Clear();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
CTRYLST.Items.Add(sdr.GetString(0));
}
}
SqlCommand cmd2 = new SqlCommand("INSERT INTO CountryNoMail (ISOCode) VALUES ('" + CTRYLST.Items.ToString() + "');", con);
cmd2.ExecuteNonQuery();
con.Close();
Assuming the sql is correct and everything is fine with the reading, eventually you can inspect the values at runtime by adding a break in the line of additems
You will be able top get back your values by using
CTRYLST.Items[0].ToString;
But it is always preferrable to use a for and cycle since you cannot be sure how many items there will be in the list box. Be careful that items are zerobased, so the first element has 0 as index, the first has 1 and so on.

Insert into Access Database on button click

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.

c# register form mysql insert

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();

User name can not contain null value

I am trying to insert two values to mysql database through two textboxes using WPF and C#. I am connecting to the database successfuly but when I try to insert the data I get error: Column "user_name" can not be null. What is really confusing be is that I am entering data in the first and the second textboxes. It seems that the data to inserted in the textboxes is not passed. My question is do you know where is the problem and how to fix it?
PS: my database is very simple contain id as int16 auto incremented, name as varchar100 and user_password as varchar100
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("host=tara.rdb.superhosting.bg;user=sozopouk;password=27051996;database=sozopouk_test2;");
MySqlDataAdapter da = new MySqlDataAdapter();
da.InsertCommand = new MySqlCommand("Insert into niki2 values (#id,#name, #user_password)", con);
da.InsertCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value=textBox2.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
con.Close();
}
Guys after I did couple of changes I am getting this error message:
Unknown column 'name' in 'field list'
Here is edited code:
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("host=tara.rdb.superhosting.bg;user=sozopouk;password=27051996;database=sozopouk_test2;");
MySqlDataAdapter da = new MySqlDataAdapter();
da.InsertCommand = new MySqlCommand("INSERT INTO niki (name, user_password) VALUES (#name, #user_password)", con);
da.InsertCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value=textBox2.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
con.Close();
}
When I replace name with user_name and try to insert data I get an error ** Column "user_name" cannot be null**
The affected line is :
da.InsertCommand.ExecuteNonQuery();
Do you have any idea how to solve it?
Look at your code:
da.InsertCommand.Parameters.Add("#user_id", MySqlDbType.Int16).Value = "";
da.InsertCommand.Parameters.Add("#user_name", MySqlDbType.VarChar).Value = "";
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value =
textBox2.Text;
Now look at what you've said:
It seems that the data to inserted in the textboxes is not passed.
Look at the code again. Look at the value being used for user_name (and indeed user_id). How is that using a textbox value? How are you expecting the data from textBox1 to get to the database when your code never mentions it?
Additionally, as sblom mentions in comments, I'd encourage you to use explicit column names - at which point you won't need to specify anything for user_id, which I assume is an auto-generated identity column anyway. (It therefore doesn't make sense to try to insert an empty value into it.) It's not clear why you're trying to use an empty string as a value for an Int16 column, either...
EDIT: For your edited code:
da.InsertCommand = new MySqlCommand(
"INSERT INTO niki (name, user_password) VALUES (#name, #user_password)", con);
Given your first error, the column is user_name, not name...
Can you just check what table you want to use exactly?
in your actual question it was
da.InsertCommand = new MySqlCommand("Insert into **niki2** values (#id,#name, #user_password)", con);
and in updated question the table name is changed to
da.InsertCommand = new MySqlCommand("INSERT INTO **niki** (name, user_password) VALUES (#name, #user_password)", con);
I feel you have two tables you are playing with and are confused
seems like
name is in niki2 and
user_name is in niki probably your actual table.
I am sure no one can answer with this much ambiguity
Try
For Table niki
da.InsertCommand = new MySqlCommand("INSERT INTO niki (user_name, user_password) VALUES (#user_name, #user_password)", con);
For Table niki2
da.InsertCommand = new MySqlCommand("INSERT INTO niki2 (name, user_password) VALUES (#name, #user_password)", con);
OR Reversal
Luck
You haven't specified in the insert statement in which fields the values should be stored, so the values will end up in the first three fields in the order that you specified, regardless of their names. I guess that the user name field is the fourth, so it doesn't get a value, thus being null.
Specify which fields should be used:
da.InsertCommand = new MySqlCommand("INSERT INTO niki (user_id, user_name, user_password) VALUES (#user_id,#user_name, #user_password)", con);
finally I find the problem causing me this exception. As you can see my old code:
da.InsertCommand = new MySqlCommand("INSERT INTO niki (name, user_password) VALUES (#name, #user_password)", con);
da.InsertCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value=textBox2.Text;
enter code here
What I did was to replace the
# with ?
And basically my code looked like :
da.InsertCommand = new MySqlCommand("INSERT INTO niki (name, user_password) VALUES (?name, ?user_password)", con);
da.InsertCommand.Parameters.Add("?name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("?user_password", MySqlDbType.VarChar).Value=textBox2.Text;
enter code here
Thanks to all who involved in the discussion!

System.Data.OleDb.OleDbException: Number of query values and destination fields are not the same

I received some help which I much appreciate to insert info into a database using paramaters as it is better practice I believe to do this.
I do however get the following error 'Number of query values and destination fields are not the same'. Not sure as to why it is happening.
The code seems perfectly fine and the database.
[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb"));
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO bookRated([title], [rating], [review], [frnISBN], [frnUserName])VALUES(#title, #rating. #review, #ISBN, #userName)";
//adding my parameters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#title", title),
new OleDbParameter("#rating", rating),
new OleDbParameter("#review", review),
new OleDbParameter("#ISBN", ISBN),
new OleDbParameter("#userName", userName),
});
cmd.ExecuteNonQuery();
conn.Close();
}
Advice perhaps as to why this error exist?
Kind regards
Arian
There is a . (period) instead of a , (comma) in your INSERT statement after the #rating parameter.
Change the . to comma.
INSERT INTO bookRated([title], [rating], [review], [frnISBN], [frnUserName])
VALUES(#title, #rating, #review, #ISBN, #userName)
I think this may be as simple as that a period has been put in place of a comma where the parameters are specified:
#rating. #review
should be:
#rating, #review

Categories

Resources