Microsoft Access Engine - c#

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

Related

Inserting Data From C# Form Into Linked Database?

I'm building an application using C# and have decided to go with a windows Form. The goal is to have a user register and be able to login with their login credentials they set up in the registration form.
Registration Form:
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
connetionString = #"Data Source=THANATOS\SQLEXPRESS01;Initial Catalog=LoginDatabase;Integrated Security=True";
SqlConnection cnn = new SqlConnection(connetionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.Parameters.AddWithValue("#FirstName", first_NameTextBox.Text);
cmd.Parameters.AddWithValue("#LastName", last_NameTextBox.Text);
cmd.Parameters.AddWithValue("#Username", usernameTextBox.Text);
cmd.Parameters.AddWithValue("#Password", passwordTextBox.Text);
cmd.Parameters.AddWithValue("#EmailAddress", email_AddressTextBox.Text);
cmd.Parameters.AddWithValue("#PhoneNumbers", passwordTextBox.Text);
cmd.CommandText = ("INSERT INTO UserRegiatration VALUES #FirstName, #LastName, #Username, #Password, #EmailAddress, #PhoneNumbers)");
try
{
cnn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("You Have Been Registered!");
cnn.Close();
}
catch (System.Exception ex)
{
MessageBox.Show("Please Try Again At A Later Time.");
}
}
This is what I have so far but I can't get the information the user enters in the text boxes to post to the database upon the button click event happening.
Any idea what I need to include or remove to improve this?
You missed a (:
INSERT into UserRegiatration VALUES
(#FirstName,#LastName,#Username,#Password,#EmailAddress,#PhoneNumbers)
^
Also, did you mean to write UserRegistration or is the table really called UserRegiatration?
In some cases you should have your table name should be surrounded in brackets.
It would look like:
INSERT into [UserRegiatration] VALUES
(#FirstName,#LastName,#Username,#Password,#EmailAddress,#PhoneNumbers)
I rewrote my tables and did some more research, it turns out, I was missing the part of the statement which identified which specific columns the information was supposed to be inserted into. This is what is now working for me. Thanks for the guidance and the troubleshooting advice.
private void registerButton_Click(object sender, EventArgs e)
{
string connetionString = null;
connetionString = #"Data Source=THANATOS\SQLEXPRESS01;Initial Catalog=LoginDatabase;Integrated Security=True";
try
{
using (SqlConnection connection = new SqlConnection(connetionString))
{
if (connection.State == ConnectionState.Closed) // Checking connection status, if closed then open.
{
connection.Open();
this.Hide();
}
String query = "INSERT INTO dbo.[Table] (FirstName,LastName,Username,Password,Email,PhoneNum) VALUES (#FirstName,#LastName,#Username,#Password,#Email,#PhoneNum)";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#FirstName", firstNameTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#LastName", lastNameTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#Username", usernameTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#Password", passwordTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#Email", emailTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#PhoneNum", phoneNumTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
int result = cmd.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error inserting data into Database!"); // If error, display message.
}
}
}
catch (Exception ex)
{
string v = ex.Message;
throw ex;
}
}
private void phoneNumLabel_Click(object sender, EventArgs e)
{
}
}
}

fatal error encountered during command execution in c#.net mysql

I have tried the code below when I am going to click Save button I got the error of "fatal error encountered during command execution" I rechecked more than two times but unfortunately error not go away. please, anyone kindly fix this error.
private void button1_Click(object sender, EventArgs e)
{
string cid, lname, fname,street,city,state,phone,date,email,aco,actype,des,bal;
cid = label14.Text;
lname = textBox1.Text;
fname = textBox2.Text;
street = textBox3.Text;
city = textBox4.Text;
state = textBox5.Text;
phone = textBox6.Text;
date = dateTimePicker1.Text;
email = textBox8.Text;
aco = textBox7.Text;
actype = comboBox1.Text;
des = textBox10.Text;
bal = textBox11.Text;
con.Open();
MySqlCommand cmd = con.CreateCommand();
MySqlTransaction transaction;
transaction = con.BeginTransaction();
StringBuilder cmdText = new StringBuilder();
cmdText.AppendLine("INSERT into customer (custid,lastname,firstname,street,city,state,phone,date,email) VALUES (#custid,#lastname,#firstname,#street,#city,#state,#phone,#date,#email)");
cmdText.AppendLine("INSERT into account(accid,custid,acctype,description,balance) VALUES (#accid,#custoid,#acctype,#description,#balance)");
cmd.CommandText = cmdText.ToString();
cmd.Connection = con;
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("#custid", cid);
cmd.Parameters.AddWithValue("#lastname", lname);
cmd.Parameters.AddWithValue("#firstname", fname);
cmd.Parameters.AddWithValue("#street", street);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#accid", aco);
cmd.Parameters.AddWithValue("#cusotid", cid);
cmd.Parameters.AddWithValue("#acctype", actype);
cmd.Parameters.AddWithValue("#description", des);
cmd.Parameters.AddWithValue("#balance", bal);
try
{
cmd.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Transaction Suceess");
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I have seen many developers encountering errors with their SQL because they are using AddWithValue on their SqlCommand. The issue with this is that the command doesn't know the data type of your sql command parameter.
You should use SqlParameterCollection.Add Method (String, SqlDbType, Int32) to specify the data type of the parameter. Refer to SqlDbType Enumeration for the SqlDbType enumeration.
Usage:
cmd.Parameters.Add("#custid", SqlDbType.Int).Value = cid;
cmd.Parameters.Add("#lastname", SqlDbType.Text).Value = lname;
P.S. I am assuming that there are no issues with your SQL connection string.

why isn't my c# insert query working?

what is the problem in my code?
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\extract step one\extract1.accdb;Persist Security Info=True";
String kerdes = Convert.ToString(textBox1.Text);
String valaszok = Convert.ToString(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(#kerdes, #valaszok)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#kerdes", OleDbType.VarChar).Value = kerdes;
cmd.Parameters.Add("#valaszok", OleDbType.VarChar).Value = valaszok;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
When I click the button it says:
Microsoft Office Access Database Engine
I made the database with Access. Any ideas?
OleDbCommand does not support named parameters - use ? instead:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");
I would also wrap both the command and connection in using blocks to ensure that the resources are disposed of properly.
You need to change your parameters to:
cmd.Parameters.AddWithValue("#kerdes", kerdes);
cmd.Parameters.AddWithValue("#valaszok", valaszok);
This needs to be done in addition to the above comment of changing your query to:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");

insert into a ms access database

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;

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.

Categories

Resources