Connecting to MS Access - c#

I am trying to connect my small C# program which has only one Insert Query with MS Access database. I followed up some codes in Internet but i couldn't get it right.
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\HP\Desktop\victoriy\Database1.accdb);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "Insert into Na(FirstName,LastName)Values('" + textBox1.Text + "','" + textBox2.Text + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
MessageBox.Show("Record Submitted", "Congrats");
con.Close();
}
}
}

Related

I get an error connecting to a MS Access database in C# [duplicate]

This question already has answers here:
ExecuteNonQuery: Connection property has not been initialized.
(7 answers)
Closed 2 years ago.
I am trying to connect to a MS Access database with my Windows Forms application, but I get this error:
Error : ExecuteNonQuery: Connection property has not been intialized"
Please help
this is the code::
namespace logintrial4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\shiwa\source\repos\logintrial4\bin\Debug\log4.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand("insert into log4 values('" + textBox1.Text + "','" + textBox2.Text + "')");
cmd.ExecuteNonQuery();
MessageBox.Show("Success");
con.Close();
}
}
}
You missed a line ,you have to set connection to cmd after initializing cmd
cmd.Connection = foo;
Complete code :
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\shiwa\source\repos\logintrial4\bin\Debug\log4.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand("insert into log4 values('" + textBox1.Text + "','" + textBox2.Text + "')");
cmd.Connection = con;
cmd.ExecuteNonQuery();
MessageBox.Show("Success");
con.Close();

What am I doing wrong with this C# .NET WinForms application?

I am trying to edit an Access DB_. For some reason I cannot insert anything. I believe my code is correct. The connection string is correct (though for security purposes I put a fake one for this post). At the end, I do not get the MessageBox like I am supposed to at the end of the function. Nothing was added to the Access DB either.
Any reason why this might be?
namespace TestBuild
{
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb");
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table1 values('"+textBox1.Text+"','"+textBox2.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record inserted successfully");
}
}
}
Suggestion - please consider refactoring your code as follows, and step through it, a line at a time, in the MSVS debugger:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb";
private void Button1_Click(object sender, EventArgs e)
{
string sql = "insert into table1 values('" + textBox1.Text + "','" + textBox2.Text + "')";
OleDbCommand cmd= new OleDbCommand(sql);
using (OleDbConnection con = new OleDbConnection(connString)) {
cmd.Connection = conn;
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("record inserted successfully");
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex.Message);
}
}
}
PS:
If you wanted to use prepared statements, you'd change your code to something like this:
string sql = "insert into table1 values(#param1, #param2)";
...
cmd.Parameters.AddWithValue("#param1", textBox1.Text);
cmd.Parameters.AddWithValue("#param1", textBox2.Text);
con.Open();
cmd.Prepare();
cmd.ExecuteNonQuery();
You can read more about techniques and guidelines for mitigating SQL injection here:
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
Here is another good article:
Best Practices for Using ADO.NET (MSDN)

A get or set accessor expected

I am getting get or set accessor excepted
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\KARTHICK\Documents\test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table1 values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record inserted successfully");
}
public void display
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from table1";
cmd.ExecuteNonQuery();
DataTable dt=new DataTable();
SqlDataAdapter dt= new SqlDataAdapter(cmd);
da.fill(dt);
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
display();
}
}
}
You have some mistakes:
Add () to the end of public void display
Duplicate variable named dt at SqlDataAdapter dt= new SqlDataAdapter(cmd);
da variable is not defined at da.fill(dt);

C# - Connecting to an Access MDB file using WPF (The ConnectionString Property has not been initialized)

Let me start by saying I've only been coding C# for about 3-4 month.
I am trying to get a basic understanding of how databases are accessed within Visual studio so that I can both insert, update and delete data. I have tried various different tests and I think I've come to the conclusion that there's something about WPF's that OleDb doesn't quite like. I have created 2 identical projects, one using Windows Forms and another using WPF. The Windows Forms version of the project works absolutely fine however the WPF project does not, giving me the error
"The ConnectionString Property has not been initialized"
I have no idea how to fix this. I've been scouring the internet for the best part of 12 hours and still had absolutely no success.
Here is the original code for the WPF file. It is the same as the Windows Form code
public partial class MainWindow : Window
{
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
public MainWindow()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cn.ConnectionString = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\MarkB\Documents\testing.mdb";
cmd.Connection = cn;
loaddata();
}
private void loaddata()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
listBox4.Items.Clear();
try
{
string q = "select * from info";
cmd.CommandText = q;
cn.Open();
dr = cmd.ExecuteReader();
if(dr.HasRows)
{
while(dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
listBox3.Items.Add(dr[2].ToString());
listBox4.Items.Add(dr[3].ToString());
}
}
dr.Close();
cn.Close();
}
catch(Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if(l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
listBox3.SelectedIndex = l.SelectedIndex;
listBox4.SelectedIndex = l.SelectedIndex;
}
}
private void button1_Click(object sender, EventArgs e)
{
if ((textBox1.Text!="") && (textBox2.Text!=""))
{
string q ="insert into info (firstname,surname,address) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text +"')";
dosomething(q);
textBox1.Text = null;
textBox2.Text = null;
textBox3.Text = null;
}
}
private void dosomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
MessageBox.Show("Data Saved");
cn.Close();
loaddata();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
if(listBox1.SelectedIndex !=-1)
{
string q = "delete from info where id =" + listBox1.SelectedItem.ToString();
dosomething(q);
}
}
}
If anyone can help it would be greatly appreciated. I know the problem must stem from the connection aspect of the code
The error suggests that the connection is being called at some point BEFORE the connection string has been passed to it. Maybe try setting the connection string right at the top when you first instantiate the OleDbConnection object:
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Users\\MarkB\\Documents\\testing.mdb");
Then create a new cmd object everytime you need it (rather than once at the top):
string query = "select * from somethingorother";
OleDbCommand cmd = new OleDbCommand(query, cn);

ExecuteNonQuery: Connection property has not been initialized (access database)

what's wrong with my code?I just want to add data into access database but it show ExecuteNonQuery:
Connection property has not been initialized.
It's pretty weird because in other project code similar to this works just fine.
OleDbCommand command = new OleDbCommand();
OleDbConnection connect = new OleDbConnection();
OleDbDataReader reader;
public Absen()
{
InitializeComponent();
}
MainForm form_utama;
private void Absen_Load(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Visual Studio Project\Minor baru - back up\Minor baru\Absensi.accdb;Persist Security Info=False;";
}
private void button1_Click(object sender, EventArgs e)
{
if (idkaryawantxt.Text != "")
{
string q = "insert into tableAbsensi (ID,ID_divisi,Waktu,Tanggal) values ('" + idkaryawantxt.Text.ToString() + "','" + iddivisitxt.Text.ToString() + "','" + (DateTime.Now.ToString("hh:mm :")) + "','" + (DateTime.Now.ToString("MM-dd-yyyy")) + "')";
dosomething(q);
}
}
private void dosomething(String q)
{
try
{
connect.Open();
command.CommandText = q;
command.ExecuteNonQuery();
connect.Close();
}
catch (Exception e)
{
connect.Close();
MessageBox.Show(e.Message.ToString());
}
}
You didn't set your Command's Connection property
command.Connection = connect;
Before execute your command you should set it as the error said

Categories