insert into a ms access database - c#

i'm realising a litel program with windows forms c#, that saves data in ms ACCESS database.
i write this code
OleDbConnection connect = new OleDbConnection();
private void button1_Click(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Zied\Documents\Visual Studio 2010\Projects\testerMSAcceess\testerMSAcceess\bin\Debug\zimed.mdb";
string fname = textBox1.Text;
string lname = textBox2.Text;
connect.Open();
OleDbCommand cmd = new OleDbCommand(" INSERT INTO user ([nom],[prenom]) VALUES (#fname,#lname)",connect);
if (connect.State == ConnectionState.Open)
{
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
connect.Close();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("erreur" + ex.Source);
connect.Close();
}
}
else
{
MessageBox.Show("probleme connection");
}
}
and i got this error when executing it
"error in insert methode"
i have not idea the error in insert request. have you an idea

Try this. I added the using-statements and [ ]-brackets to the query string.
string fname = textBox1.Text;
string lname = textBox2.Text;
using(OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Zied\Documents\Visual Studio 2010\Projects\testerMSAcceess\testerMSAcceess\bin\Debug\zimed.mdb"))
using(OleDbCommand cmd = new OleDbCommand("INSERT INTO [user] ([nom],[prenom]) VALUES (#fname,#lname)", conn))
{
try
{
conn.Open();
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
}
catch (Exception ex) { MessageBox.Show("Erreur" + ex.Source); }
finally { if (conn.State == ConnectionState.Open) { conn.Close(); } }
}

The OLE DB .NET Provider uses positional parameters that are marked with a question mark (?) instead of named parameters.So, Try to use ? instead of named parameter. for example.
INSERT INTO [user] ([nom],[prenom]) VALUES (?,?)
comand.Parameters.Add("nom", OleDbType.VarChar).Value = fname;

Related

Microsoft Access Engine

I'm trying to add data from Visual Studio to Access in C#. Every time I click the button to save the data an error message pops up saying "Microsoft Database Engine". I have no clue where the problem is. I pasted the code below:
private void btnsave_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\My Monroe\Semester 5\Advanced Programming\Final Project\WindowsFormsApplication1\WindowsFormsApplication1\Final exam .accdb";
string fname = first_NameTextBox.Text;
string lname = last_NameTextBox.Text;
string snum = sSNTextBox.Text;
string city = cityTextBox.Text;
string state = stateTextBox.Text;
string telnum = telephone__TextBox.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Customers(First Name, Last Name, SSN,City,State,Telephone# )" + " values(#fname,#lname,#snum,#city,#state,#telnum)", connect);
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#fname", OleDbType.Char, 20).Value = fname;
cmd.Parameters.Add("#lname", OleDbType.Char, 20).Value = lname;
cmd.Parameters.Add("#snum", OleDbType.Numeric, 20).Value = snum;
cmd.Parameters.Add("#city", OleDbType.Char, 20).Value = city;
cmd.Parameters.Add("#state", OleDbType.Char, 20).Value = state;
cmd.Parameters.Add("#telnum", OleDbType.Numeric, 20).Value = telnum;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
A few things to check. Firstly change the catch to
MessageBox.Show(ex.Message);
This will be much more informative!
Secondly on which line does the error get thrown? Thirdly, please check your connection string. When I attach to access my string is always of the form:
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DBFullPath\DBName.accdb;Jet OLEDB:Engine Type=5;Persist Security Info=False;"
if there is no password or
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DBFullPath\DBName.accdb;Jet OLEDB:Engine Type=5;Jet OLEDB:Database Password = password;"
if there is one.
Finally, do you really have a telephone field as numeric? What happens with numbers that start with 0 or international ones with +?
EDIT
Sorry I think you misunderstood me. What I wanted you to do, was to amend the catch so that it reads (in full):
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}

How can I insert and save data into database using Visual Studio and C#?

public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string q2 = "insert into gym.dbo.customer (name, weight, height, add_class, gender, fees) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.comboBox1.Text + "','" + this.comboBox2.Text + "','" + this.comboBox3.Text + " ') ;";
SqlConnection con = new SqlConnection(ss);
SqlCommand cmd = new SqlCommand(q2, con);
SqlDataReader read;
try
{
con.Open();
read = cmd.ExecuteReader();
MessageBox.Show("Welcome to our gym");
while (read.Read()) { };
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can I insert and save data into the database using Visual Studio and C#?
This code throws an error. Anyone please give the suggestion to me to solve the error.
image description
At first make sure your the data type of different column of customer table.
Then make sure what type of data you have to save for combobox.
you have to get the selected value from your Combobox. combobox1,combobox2,combobox3 retuns only the class name
System.Windows.Forms.ComboBox
Besides others, it is recommended to use parameter .. like this:
You can follow this example
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES (#Name,#Fullname,#Password,#Email, #Gander)"))
{
cmd.Connection = con;
cmd.Parameters.Add("#Name", txtfname.Text);
cmd.Parameters.Add("#Fullname", txtfname.Text);
cmd.Parameters.Add("#Password", txtpass.Text);
cmd.Parameters.Add("#Email", txtemail.Text);
cmd.Parameters.Add("#Gander", comboBox1.GetItemText(comboBox1.SelectedItem));
con.Open()
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception e)
{
MessageBox.Show("Error during insert: " + e.Message);
}
}
}
The comments are getting a bit busy, so this is the sort of thing you need to do (including parameterising the query):
Specifically, you don't need a reader for an insert statement as it doesn't return a result set.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
var sql = "insert into dbo.customer ...";
using (var con = new SqlConnection(ss))
{
var cmd = new SqlCommand(sql , con);
con.Open();
cmd.ExecuteScalar();
MessageBox.Show("Welcome to our gym");
}
}
Hi check that customer table is available in gym Database.
else try this link
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into customer (name,weight,height,add_class,gender,fees) values(#name,#weight,#height,#add_class,#gender,#fees)", con);
cmd.Parameters.AddWithValue("name", this.textBox1.Text);
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
I found that your connection string declaration is wrong
public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
need to update like below
public string ss = "Data Source=abc\\SQLEXPRESS;Initial Catalog=gym; user id=sa; Password=123456";
Data source will be not be D, It should be Server name.
enter image description here

The error says "The ConnectionString property has not been initialized" in c#

this code is for the combo box where i want to select some index to show it to my textboxes.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
cmd.Connection = conn;
string query = "SELECT * FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'";
db.connectDB();
db.da.SelectCommand = new OleDbCommand(query, db.conn);
db.executeQryCommand(query, false);
maxRecord = db.ds.Tables[0].Rows.Count;
loadRecords(recordCounter);
cmd.CommandText = query;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["Gname"].ToString();
textBox2.Text = dr["Gcontactno"].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
//My program is completely running but not in this section. :(
Is you made an connection between your application and database source using conn object ? You might be used conn object as a connection object but before this was you initialized you Connection ?
Simpy use like
"SqlConnection conn=new SqlConnection("Connection_Source");"
here is your error.
You have to define the connection string for the connection, here i suggest you one best method for executing command.
using (OleDbConnection conn = new OleDbConnection("yourconnectionString"))
{
conn.Open();
using (OleDbCommand cmd =new OleDbCommand("your query text", conn))
{
// execute your command
}
}
If its just to select value from comboBox and display in textBox , then below code will help you...
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT Gname,Gcontactno FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}

Insert database using MS Access in C#

It doesn't have an error, but it has a message box showing Ms Access Database Engine and data not insert to database. Can anyone help me solve the problem??
namespace WindowsFormsApplication1
{
public partial class SignUp : Form
{
public SignUp()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Junz\Documents\Register - Copy.mdb";
conn.Open();
String Username = textBox1.Text;
String Password = textBox2.Text;
String Email = textBox3.Text;
String Address = textBox4.Text;
OleDbCommand cmd = new OleDbCommand("INSERT INTO Register(Username,Password,Email,Address) Values(#Username, #Password,#Email,#Address)");
cmd.Connection = conn;
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#Username", OleDbType.VarChar,20).Value = Username;
cmd.Parameters.Add("#Password", OleDbType.VarChar,20).Value = Password;
cmd.Parameters.Add("#Email", OleDbType.VarChar,20).Value = Email;
cmd.Parameters.Add("#Address", OleDbType.VarChar,20).Value = Address;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
}
ExecuteNonQuery() will return int value representing number of rows updated into Database.
if the returned value is 0 you can Display a Message saying DATA NOT ADDED
Try This: write your try block as below.
try
{
if(cmd.ExecuteNonQuery()>0)
MessageBox.Show("DATA ADDED");
else
MessageBox.Show("DATA NOT ADDED");
conn.Close();
}
how about this hope it helps
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Junz\Documents\Register - Copy.mdb";
conn.Open();
String Username = textBox1.Text;
String Password = textBox2.Text;
String Email = textBox3.Text;
String Address = textBox4.Text;
conn.Open();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Register(Username,Password,Email,Address) Values(#Username, #Password,#Email,#Address)";
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#Username", OleDbType.VarChar,20).Value = Username;
cmd.Parameters.Add("#Password", OleDbType.VarChar,20).Value = Password;
cmd.Parameters.Add("#Email", OleDbType.VarChar,20).Value = Email;
cmd.Parameters.Add("#Address", OleDbType.VarChar,20).Value = Address;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
Add this to your catch
catch (OleDbException ex){
MessageBox.Show(ex.Message);
conn.Close();
}
And try to insert again, maybe u can see the exact error now.
Good luck.

C# SQL Server CE - Update won't work

I'm trying to finish a college project that requires a program to interact with a database.
Some of my naming is a little odd, but don't worry!
I'm trying to use a single submit button to either update or insert to the database.
Main issue is that I can't get an update to work though when I changed my code to try and fix it, I made it worse. Here is what I currently have.
private void btn_submit_Click(object sender, EventArgs e)
{
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT TaskCode FROM TaskCode;";
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
SqlCeDataReader reader;
reader = c1.ExecuteReader();
if (reader.Read())
{
try
{
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, TaskDescription = #TaskDescription = WHERE TaskCode = #TaskCode;";
SqlCeCommand c = new SqlCeCommand(taskUpdate, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been updated");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
else
{
try
{
string taskInsert = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
SqlCeCommand c = new SqlCeCommand(taskInsert, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
}
}
Has anyone got any ideas why I am getting an error on the c.ExecuteQuery line?
If I remove said line, it will not throw an exception, but it will not update the database.
Thanks
You have a simple syntax error in your update query just before the where statement.
There is an invalid equal sign
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
Your query also could be simplified with
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT COUNT(*) FROM TaskCode";
string cmdText;
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
int count = (int)c1.ExecuteScalar();
if (count > 0)
{
// Here there is no point to update the TaskCode. You already know the value
// Unless you have a different value, but then you need another parameter
// the 'old' TaskCode.....
cmdText = "UPDATE TaskCode SET " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
}
else
{
cmdText = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
}
try
{
SqlCeCommand c = new SqlCeCommand(cmdText, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
MessageBox.Show(count > 0 ? "Record has been updated" : "Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
Not sure if it is the only problem, but you have an equal (=) sign before the WHERE keyword.

Categories

Resources