Adding to a Database - C# with Access - c#

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.)

Related

OleDb Update database.mdb

When i use the CustomButton for to save the "Full_Name" in the Database [Rooms] => Person then there is just nothing happen. Also if i use the try & catch function, there will be no Exception.
The field in the Database stays Empty.
When i show the required variable in the MessageBox (idPlus2, Full_Name) then it throws me back the right informations.
So i think the problem must be in the UPDATE Sql string but i don't know whats wrong.
private string connstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\....mdb";
//Path anonymous
string Full_Name;
[Obsolete]
private void customButton1_Click(object sender, EventArgs e)
{
conn = new OleDbConnection(connstr);
conn.Open();
strSQL = "SELECT * FROM [Guests] WHERE ID = ?";
cmd = new OleDbCommand(strSQL, conn);
da = new OleDbDataAdapter(cmd);
int id = CustomComboBox1.SelectedIndex;
int idPlus = id + 1;
cmd.Parameters.Add("?", idPlus);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Full_Name = reader["Vorname"].ToString() + ' ' + reader["Nachname"].ToString();
}
reader.Close();
string insertQuery = #"UPDATE [Rooms] SET Person = #Full_Name WHERE ID = ?";
cmd = new OleDbCommand(insertQuery, conn);
int id2 = customComboBox2.SelectedIndex;
int idPlus2 = id2 + 2;
cmd.Parameters.Add("?", idPlus2);
cmd.Parameters.Add(new OleDbParameter("#Full_Name", Full_Name));
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
LoadTheme();
}
I have the answer
cmd.Parameters.Add("?", OleDbType.VarChar, 255).Value = CustomComboBox1.Texts;
cmd.Parameters.Add("?", idPlus2);
With OleDb you have to use ? for each variable or object which should be added to the database. That means that you can't specify the variable by name in the SQL string. You have to use the same order as the SQL string in C # code to insert the parameters.

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

How to dynamically Add rows into Table?

I have a Contact Form where the user can add 1 or more (max 5) contacts. Once the user clicks save, the program needs to check the number of contacts submitted and insert into the Contacts_Table accordingly as separate rows. For example, if the user provides 3 contacts, 3 rows should be inserted into the database. The problem here is am able to achieve the goal, but am trying to reduce the number of code lines.
Here is the sample code:
string internalContact = "insert into InternalContact("
+ "Phone, FirstName, Surname)"
+ "values (#Phone, #FirstName, #Surname)";
using (OleDbConnection conn1 = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd1 = new OleDbCommand(internalContact, conn1))
{
conn1.Open();
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.Add("FirstName", OleDbType.VarChar).Value = TextBox34.Text;
cmd1.Parameters.Add("Surname", OleDbType.VarChar).Value = TextBox42.Text;
cmd1.Parameters.Add("Phone", OleDbType.VarChar).Value = TextBox45.Text;
cmd1.ExecuteNonQuery();
if (TextBox64.Text != "")
{
cmd1.Parameters.Clear();
cmd1.Parameters.Add("FirstName", OleDbType.VarChar).Value = TextBox64.Text;
cmd1.Parameters.Add("Surname", OleDbType.VarChar).Value = TextBox65.Text;
cmd1.Parameters.Add("Phone", OleDbType.VarChar).Value = TextBox69.Text;
cmd1.ExecuteNonQuery();
}
conn1.Close();
}
}
I would create a struct list and pass all contact info to the method.
struct contactInfo
{
public string FirstName;
public string Surname;
public string Phone;
}
private void insertContacts (List<contactInfo> pList)
{
using (OleDbConnection conn1 = new OleDbConnection(ConnString))
{
conn1.Open();
foreach (contactInfo info in pList)
{
using (OleDbCommand cmd1 = new OleDbCommand(internalContact, conn1))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.Add("FirstName", OleDbType.VarChar).Value = info.FirstName;
cmd1.Parameters.Add("Surname", OleDbType.VarChar).Value = info.Surname;
cmd1.Parameters.Add("Phone", OleDbType.VarChar).Value = info.Phone;
cmd1.ExecuteNonQuery();
}
}
conn1.Close();
}
}

OleDb connection to an Access database

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;";

ExecutreNonQuery and Update Statement

Receiving this error when I try saving.
Incorrect Syntax near the word update.
Seems like an obvious fix but I can't seem to find it. Hoping fresh eyes will help! Thanks
protected void btnSave_Click(object sender, EventArgs e)
{
Button EditButton = (Button)EditLoginView.FindControl("EditButton");
Button SaveButton = (Button)EditLoginView.FindControl("SaveButton");
TitleLanguage.ActiveViewIndex = 0;
LanguageView.ActiveViewIndex = 0;
EditButton.Visible = true;
SaveButton.Visible = false;
//update the file in the database
string strQuery = "UPDATE pages SET en_content = #en_Content, fr_Content = #fr_content, fr_Title=#fr_title, en_Title=#en_title, update=#update WHERE link_title = #link_title";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#en_title", SqlDbType.VarChar).Value = Edit_EnglishT.Text;
cmd.Parameters.Add("#fr_title", SqlDbType.VarChar).Value = Edit_FrenchT.Text;
cmd.Parameters.Add("#en_content", SqlDbType.VarChar).Value = Edit_English.Text;
cmd.Parameters.Add("#fr_content", SqlDbType.VarChar).Value = Edit_French.Text;
cmd.Parameters.Add("#update", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("#link_", SqlDbType.VarChar).Value = linktitle;
UpdateData(cmd);
}
private Boolean UpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["randolphConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
UPDATE is a reserved keyword in T-SQL. You should use it with square brackets like [UPDATE]
Like;
string strQuery = #"UPDATE pages SET en_content = #en_Content, fr_Content = #fr_content, fr_Title=#fr_title, en_Title=#en_title,
[update]=#update WHERE link_title = #link_title";
^^^^^^^^
As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.
Also change your
cmd.Parameters.Add("#link_", SqlDbType.VarChar).Value = linktitle;
to
cmd.Parameters.Add("#link_title", SqlDbType.VarChar).Value = linktitle;
Because you declared your parameter name as #link_title not #link_ in your strQuery.
EDIT: For clarification, you don't need to use a method (UpdateData) for that such a process. Just use like this;
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["randolphConnectionString"].ConnectionString;
using(SqlConnection con = new SqlConnection(strConnString))
using(SqlCommand cmd = con.CreateCommand())
{
string strQuery = #"UPDATE pages SET en_content = #en_Content, fr_Content = #fr_content, fr_Title=#fr_title, en_Title=#en_title, [update]=#update WHERE link_title = #link_title";
cmd.CommandText = strQuery;
cmd.Parameters...;
.....
.....
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
You define the field update which is a reserved keyword.
Try [update] instead like in this sample:
UPDATE pages
SET en_content = #en_Content
, fr_Content = #fr_content
, fr_Title=#fr_title
, en_Title=#en_title
, [update]=#update
WHERE link_title = #link_title
In your last parameter, you use #link_title
but in the Parameter.Add, you use:
cmd.Parameters.Add("#link_", SqlDbType.VarChar).Value = linktitle;
Try to change for this one:
cmd.Parameters.Add("#link_title", SqlDbType.VarChar).Value = linktitle;

Categories

Resources