OleDb connection to an Access database - c#

I've been trying to write to a database and save to the file but I cant get it to work, can't tell why either.
The error I get is:
Exception thrown: 'System.Data.OleDb.OleDbException' in System.Data.dll
Additional information:
Could not find installable ISAM.
Here's the Code I'm running, any help/advice would be greatly appreciated
private void BtnSubmit_Click(object sender, EventArgs e)
{
OleDbConnection Conn = new OleDbConnection();
Conn.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =| DataDirectory |\\HoliPlanData.accdb; Trusted_Connection = True;";
String PayrollNo = TxtPayroll.Text;
String FirstName = TxtFirstName.Text;
String LastName = TxtLastName.Text;
String AnnualHolidayEntitlemet = TxtAHE.Text;
String DaysTakenToDate = TxtDTTD.Text;
OleDbCommand Query = new OleDbCommand("INSERT INTO Employee (PayrollNo, FirstName, LastName, AnnualHolidayEntitlement, DaysTakenToDate) Values(#PayrollNo, #FirstName, #LastName, #AnnualHolidayEntitlement, #DaysTakenToDate");
Query.Connection = Conn;
Conn.Open(); //THIS IS WHERE THE ERROR OCCURS IN CODEPROSSESS
if (Conn.State == ConnectionState.Open)
{
Query.Parameters.Add("#PayrollNo", OleDbType.VarChar).Value = PayrollNo;
Query.Parameters.Add("#FirstName", OleDbType.VarChar).Value = FirstName;
Query.Parameters.Add("#LastName", OleDbType.VarChar).Value = LastName;
Query.Parameters.Add("#AnnualHolidayEntitlement", OleDbType.VarChar).Value = AnnualHolidayEntitlemet;
Query.Parameters.Add("#DaysTakenToDate", OleDbType.VarChar).Value = DaysTakenToDate;
try
{
Query.ExecuteNonQuery();
MessageBox.Show("Data Added Successfully");
Conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
Conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}

Two issues:
Your connection string has an extra semicolon as you pointed out in comments above
Your INSERT query is missing the last parenthesis )
Compare these lines:
OleDbCommand Query = new OleDbCommand("INSERT INTO Employee (PayrollNo, FirstName, LastName, AnnualHolidayEntitlement, DaysTakenToDate) Values(#PayrollNo, #FirstName, #LastName, #AnnualHolidayEntitlement, #DaysTakenToDate");
OleDbCommand Query = new OleDbCommand("INSERT INTO Employee (PayrollNo, FirstName, LastName, AnnualHolidayEntitlement, DaysTakenToDate) Values(#PayrollNo, #FirstName, #LastName, #AnnualHolidayEntitlement, #DaysTakenToDate)");

Install AccessDatabaseEngine and try again.
Change the connection string as below.
Conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|\\HoliPlanData.accdb;Trusted_Connection = True;";

Related

C# update combobox with Database values

Hello I have a database with drivers and a combobox which is populated with the drivers. But when I add a new driver with a button Add Driver, it's added only in Microsoft Access table, not in the combobox. And once I reload the program, the new driver is deleted from the database. I also have connected the database in Data Source and I can edit the tables only from there(if I want to edit the combobox).
This is my connection with the database
private void Form1_Load(object sender, EventArgs e)
{
con = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=transportDateBase.accdb");
cmd = new OleDbCommand();
con.Open();
cmd.Connection = con;
string query = "SELECT Name FROM Drivers";
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
comboDriver.Items.Add(reader["Name"]);
}
con.Close();
and this is my Add Driver button:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ("Provider=Microsoft.ACE.Oledb.12.0;Data Source=transportDateBase.accdb");
String Id = textID.Text;
String Name = textName.Text;
String Age = textAge.Text;
String City = textCity.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Drivers (Id, Name, Age, City) Values(#Id, #Name, #Age, #City)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#Id", OleDbType.VarChar).Value = Id;
cmd.Parameters.Add("#Name", OleDbType.VarChar).Value = Name;
cmd.Parameters.Add("#Age", OleDbType.VarChar).Value = Age;
cmd.Parameters.Add("#City", OleDbType.VarChar).Value = City;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("New Driver Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
Just because you've added it to your database, doesn't mean anything else will happen.
You still need to update your UI.
Add this in after you have executed the query:
comboDriver.Items.Add(Name);
As an aside, you should also wrap the conn.Open() in a try catch as well

Execute Reader: Connection Property has not been initialized in C# and Visual Studio

I keep getting the error
ExecuteReader: Connection Property has not been initialized
in C# and Visual Studio. I have tried some solutions that I researched but they do not seem to be doing the trick.
Here is my code:
public static int AddCustomer(Customer customer)
{
MySqlConnection connection = MySqlCommand.GetConnection();
string strInsertStatement =
"INSERT Customers (Name, Address, City, State, ZipCode) " +
"VALUES (#Name, #Address, #City, #State, #ZipCode)";
MySql.Data.MySqlClient.MySqlCommand insertCommand = new MySql.Data.MySqlClient.MySqlCommand(strInsertStatement);
insertCommand.Parameters.AddWithValue("#Name", customer.strFirstName);
insertCommand.Parameters.AddWithValue("#Address", customer.strStreetName);
insertCommand.Parameters.AddWithValue("#City", customer.strCity);
insertCommand.Parameters.AddWithValue("#State", customer.strState);
insertCommand.Parameters.AddWithValue("#ZipCode", customer.strPhoneNumber);
try
{
connection.Open();
insertCommand.ExecuteNonQuery();
string strSelectStatement = "SELECT IDENT_CURRENT('Customers') FROM Customers";
MySql.Data.MySqlClient.MySqlCommand selectCommand = new MySql.Data.MySqlClient.MySqlCommand(strSelectStatement, connection);
int customerID = Convert.ToInt32(selectCommand.ExecuteScalar());
return customerID;
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
connection.Close();
}
}
What am I missing that is making this error appear?
The error says it all: Connection Property has not been set.
You have a Connection, and you have insertCommand. Nowhere in the code are you telling insertCommand to use the Connection.
insertCommand.Connection = connection;
Or, possibly, as part of its connector as you do with the Select.
You have to give the connection as second parameter to MySQlCommand:
MySql.Data.MySqlClient.MySqlCommand insertCommand =
new MySql.Data.MySqlClient.MySqlCommand(strInsertStatement, connection);
You need to set the Connection property of the command. Use the constructor that accepts a MySqlConnection.
MySql.Data.MySqlClient.MySqlCommand insertCommand = new MySql.Data.MySqlClient.MySqlCommand(strInsertStatement, connection);
In which line do you get the error? I just had a quick look at your code and think you forgot to add your connection to the insert command use the following instead:
EDIT: Put all the code here and added printing of error to console and assignment of connection.
I guess you get your error in the open() method call. There is no connect string in your solution. Don't forget to enter your credentials.
public static int AddCustomer(Customer customer)
{
MySqlConnection connection = new MySqlConnection();
connection.ConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;"
string strInsertStatement =
"INSERT Customers " +
"(Name, Address, City, State, ZipCode) " +
"VALUES (#Name, #Address, #City, #State, #ZipCode)";
MySql.Data.MySqlClient.MySqlCommand insertCommand =
new MySql.Data.MySqlClient.MySqlCommand(strInsertStatement);
insertCommand.Parameters.AddWithValue(
"#Name", customer.strFirstName);
insertCommand.Parameters.AddWithValue(
"#Address", customer.strStreetName);
insertCommand.Parameters.AddWithValue(
"#City", customer.strCity);
insertCommand.Parameters.AddWithValue(
"#State", customer.strState);
insertCommand.Parameters.AddWithValue(
"#ZipCode", customer.strPhoneNumber);
try
{
connection.Open();
insertCommand.Connection = connection;
insertCommand.ExecuteNonQuery();
string strSelectStatement =
"SELECT IDENT_CURRENT('Customers') FROM Customers";
MySql.Data.MySqlClient.MySqlCommand selectCommand =
new MySql.Data.MySqlClient.MySqlCommand(strSelectStatement, connection);
int customerID = Convert.ToInt32(selectCommand.ExecuteScalar());
return customerID;
}
catch (MySqlException ex)
{
Console.WriteLine(ex.ToString());
throw ex;
}
finally
{
connection.Close();
}
}

Adding to a Database - C# with Access

Below is the code I'm using to connect to an Access Database.
I'm trying to insert the data (which is a form the user fills in). But always the exception is caught and no data gets inserted.
I've double checked the variable names for spelling errors,they are all correct.
private void addConfirm_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\hospitalApplication\HealthCare.accdb;Persist Security Info=False;";
String name = typedName.Text;
String addr = typedAddr.Text;
String DOB = typedDOB.Text;
String phone = typedPhone.Text;
String emergency = typedEmergency.Text;
String dateOfReg = typedDateReg.Text;
String patientstatus = typedStatus.Text;
String bedNo = typedBed.Text;
String blood = typedBlood.Text;
String visit = typedVisit.Text;
String diagnosis = typedDiagnosis.Text;
String doctorID = typedDoctor.Text;
OleDbCommand cmd = new OleDbCommand("INSERT into Patients (Full Name, Address,Date of Birth,Phone No,Emergency Contact,Date of Registration,Patient Status,bedID,Blood Type,Date of Visit,Diagnosis,doctorID) Values(#name, #addr,#DOB,#phone,#emergency,#dateOfReg,#patientstatus,#bedNo,#blood,#visit,#diagnosis,#doctorID)", conn);
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#name", OleDbType.VarChar).Value = name;
cmd.Parameters.Add("#addr", OleDbType.VarChar).Value = addr;
cmd.Parameters.Add("#DOB", OleDbType.VarChar).Value = DOB;
cmd.Parameters.Add("#phone", OleDbType.VarChar).Value = phone;
cmd.Parameters.Add("#emergency", OleDbType.VarChar).Value = emergency;
cmd.Parameters.Add("#dateOfReg", OleDbType.VarChar).Value = dateOfReg;
cmd.Parameters.Add("#patientstatus", OleDbType.VarChar).Value = patientstatus;
cmd.Parameters.Add("#bedNo", OleDbType.Integer).Value = bedNo;
cmd.Parameters.Add("#blood", OleDbType.VarChar).Value = blood;
cmd.Parameters.Add("#visit", OleDbType.VarChar).Value = visit;
cmd.Parameters.Add("#diagnosis", OleDbType.VarChar).Value = diagnosis;
cmd.Parameters.Add("#doctorID", OleDbType.Integer).Value = doctorID;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
Your SQL in invalid. The spaces are confusing the query parser.
The best approach is to not use spaces in your table/column names. But if you must, then you'll need to enclose them in brackets to tell the query parser that both words identify one item. Something like this:
INSERT into Patients ([Full Name], ...
Do this for any table/column name which includes either spaces or reserved words. (You can do this for all of the table/column names if you'd like.)

MySQL C# Query trouble - Updating table

I'am having trouble with this function I'm creating to Update my database. The Update faculty member seems to work perfectly while the Updating of the person tables does not . I'm presuming that the MySQL Query isn't correct for updating the person table.
Additional INFO: My code is hooked to an GUI mock as of right now for testing purposes . the Update string with #Id.. its just to select which ID I wish to change..
public static void Update(string update,string fName, string lName, string DOB, string postCode, string address, string phoneNumber,
bool isTenured, string qualifications, string previousEmployment)
{
MySqlConnection conn;
MySqlCommand cmd;
string sql = "UPDATE person SET firstName = #FirstName , lastName = #LastName, DOB = #DOB, phoneNumber = #PhoneNumber, address = #Address, postCode = #PostCode WHERE ID =#Id;";
GetConnection(out conn, out cmd, sql);
try
{
cmd.Parameters.AddWithValue("#Id", update);
cmd.Parameters.AddWithValue("#FirstName", fName);
cmd.Parameters.AddWithValue("#LastName", lName);
cmd.Parameters.AddWithValue("#DOB", DOB);
cmd.Parameters.AddWithValue("#PhoneNumber", phoneNumber);
cmd.Parameters.AddWithValue("#Address", address);
cmd.Parameters.AddWithValue("#PostCode", postCode);
long id = (long)cmd.LastInsertedId;
sql = "UPDATE facultymember SET isTenured = #IsTenured, qualifications = #Qualifications, previousEmployment = #PreviousEmployment WHERE Person_personID=#Id";
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#IsTenured", isTenured);
cmd.Parameters.AddWithValue("#Qualifications", qualifications);
cmd.Parameters.AddWithValue("#PreviousEmployment", previousEmployment);
cmd.ExecuteNonQuery();
}
catch (NullReferenceException nre)
{
MessageBox.Show(nre.Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
try
{
MessageBox.Show("Updated");
cmd.Connection.Close();
conn.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
You forget to add #Id parameter in your second sql query.
sql = "UPDATE facultymember
SET isTenured = #IsTenured, qualifications = #Qualifications, previousEmployment = #PreviousEmployment
WHERE Person_personID=#Id";
// ^^^^
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#IsTenured", isTenured);
cmd.Parameters.AddWithValue("#Qualifications", qualifications);
cmd.Parameters.AddWithValue("#PreviousEmployment", previousEmployment);
cmd.Parameters.AddWithValue("#Id", YourIdValue);
cmd.ExecuteNonQuery();
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(ConnectionString))
using(MySqlCommand cmd = conn.CreateCommand())
{
//
}

Inserting values into a SQL Server database using ado.net via C#

I have created a simple program to insert values into the table [regist], but I keep getting the error
Incorrect syntax near ')'
on cmd.ExecuteNonQuery();:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;");
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact, " + ") VALUES (" + " #textBox1.Text, #textBox2.Text, #textBox3.Text, #textBox4.Text, #comboBox1.Text,#comboBox2.Text,#textBox7.Text" + ")", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
I am new to this and I am really confused.
As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.
Also: I would recommend to separate the click event handler from the actual code to insert the data.
So I would rewrite your code to be something like
In your web page's code-behind file (yourpage.aspx.cs)
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
InsertData(connectionString,
textBox1.Text.Trim(), -- first name
textBox2.Text.Trim(), -- last name
textBox3.Text.Trim(), -- user name
textBox4.Text.Trim(), -- password
Convert.ToInt32(comboBox1.Text), -- age
comboBox2.Text.Trim(), -- gender
textBox7.Text.Trim() ); -- contact
}
In some other code (e.g. a databaselayer.cs):
private void InsertData(string connectionString, string firstName, string lastname, string username, string password
int Age, string gender, string contact)
{
// define INSERT query with parameters
string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (#FirstName, #Lastname, #Username, #Password, #Age, #Gender, #Contact) ";
// create connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = firstName;
cmd.Parameters.Add("#Lastname", SqlDbType.VarChar, 50).Value = lastName;
cmd.Parameters.Add("#Username", SqlDbType.VarChar, 50).Value = userName;
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 50).Value = password;
cmd.Parameters.Add("#Age", SqlDbType.Int).Value = age;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar, 50).Value = gender;
cmd.Parameters.Add("#Contact", SqlDbType.VarChar, 50).Value = contact;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
Code like this:
is not vulnerable to SQL injection attacks
performs much better on SQL Server (since the query is parsed once into an execution plan, then cached and reused later on)
separates the event handler (code-behind file) from your actual database code (putting things where they belong - helping to avoid "overweight" code-behinds with tons of spaghetti code, doing everything from handling UI events to database access - NOT a good design!)
Remove the comma
... Gender,Contact, " + ") VALUES ...
^-----------------here
Following Code will work for "Inserting values into a SQL Server database using ado.net via C#"
// Your Connection string
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
// Collecting Values
string firstName="Name",
lastName="LastName",
userName="UserName",
password="123",
gender="Male",
contact="Contact";
int age=26;
// Query to be executed
string query = "Insert Into dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (#FN, #LN, #UN, #Pass, #Age, #Gender, #Contact) ";
// instance connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// add parameters and their values
cmd.Parameters.Add("#FN", System.Data.SqlDbType.NVarChar, 100).Value = firstName;
cmd.Parameters.Add("#LN", System.Data.SqlDbType.NVarChar, 100).Value = lastName;
cmd.Parameters.Add("#UN", System.Data.SqlDbType.NVarChar, 100).Value = userName;
cmd.Parameters.Add("#Pass", System.Data.SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#Age", System.Data.SqlDbType.Int).Value = age;
cmd.Parameters.Add("#Gender", System.Data.SqlDbType.NVarChar, 100).Value = gender;
cmd.Parameters.Add("#Contact", System.Data.SqlDbType.NVarChar, 100).Value = contact;
// open connection, execute command and close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
you should remove last comma and as nrodic said your command is not correct.
you should change it like this :
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source=CHANCHAL\SQLEXPRESS;initial catalog=AssetManager;user id=GIPL-PC\GIPL;password=";
con.Open();
SqlDataAdapter ad = new SqlDataAdapter("select * from detail1", con);
SqlCommandBuilder cmdbl = new SqlCommandBuilder(ad);
DataSet ds = new DataSet("detail1");
ad.Fill(ds, "detail1");
DataRow row = ds.Tables["detail1"].NewRow();
row["Name"] = textBox1.Text;
row["address"] =textBox2.Text;
ds.Tables["detail1"].Rows.Add(row);
ad.Update(ds, "detail1");
con.Close();
MessageBox.Show("insert secussfully");
}

Categories

Resources