Hi am new to C# and am trying to connect to .accdb access 2010 database
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection connect = new OleDbConnection();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Web Develop\Documents\Storekeeper\storekeeper.accdb;Persist Security Info=False;";
connect.Open();
MessageBox.Show("Connection open");
}
}
}
and I get this exception:
A first chance exception of type System.Data.OleDb.OleDbException occurred in System.Data.dll
The database is not in use and the path is correct what do I do?
There should be an InnerException property on the thrown exception which you can examine. It will tell you what the exact error is. To see it, you need to catch the exception, and then show the InnerException message:
private void Form1_Load(object sender, EventArgs e)
{
try
{
OleDbConnection connect = new OleDbConnection();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Web Develop\Documents\Storekeeper\storekeeper.accdb;Persist Security Info=False;";
connect.Open();
MessageBox.Show("Connection open");
}
catch (OleDbException e)
{
Messagebox.Show(e.InnerException.Message);
}
}
There is additional example code for capturing and displaying the errors embedded in an OleDbException at the MSDN page for OleDbException.
I think, this is simple. Since you on the office 2010, I believe you need: Microsoft.ACE.OLEDB.14.0
Ok. If you have Office 32 bit on a 64 bit O/S, then you're gonna have fits. Try changing the "Platform Output" to x86.
Go to your project properties and find the "Build" tab.
"Platform target" should be listed there.
Now, even if that works, you'll have to investigate the ramifications of that decision.
But at least "you would know".
EDIT--------------
Here are your permutations. And you're gonna just have to experiment with them.
The connection string, is it right or wrong. "12" vs "14" as previously mentioned.
(Sorry, the link is about Excel. Try using the suggestion from "T.S.".)
Office 32 bit being installed. I think if you tried to install "AccessDatabaseEngine_x64.exe" on that machine, it would give you a "Office version not right" error.
So because of #2, you gotta install "AccessDatabaseEngine.exe". Which is 32 bit.
The "Platform Output". Now I ~~think~~ because of #3, you need to experiment with setting it to x86.
Try putting it back to x86, and then trying the "12" vs "14" in the connection string.
EDIT-----------------
I pulled a file off the internet.
Oren.accdb
from
http://old.cba.ua.edu/~jomason/ac289/289AccessFiles.html
And I coded this up on my machine. And it works.
private void button1_Click(object sender, EventArgs e)
{
try
{
using (OleDbConnection connect = new OleDbConnection())
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\folder1\data\Oren.accdb;Persist Security Info=False;";
connect.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connect;
cmd.CommandText = "Select * from Agreement";
StringBuilder sb = new StringBuilder();
IDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
sb.Append(string.Format("{0}, {1}", reader[0].ToString(), reader[1].ToString()) + System.Environment.NewLine);
}
reader.Close();
ReportMessage(sb.ToString());
}
}
catch (System.Data.OleDb.OleDbException lolex)
{
ReportException(lolex);
}
catch (Exception ex)
{
ReportException(ex);
}
}
private void ReportException(Exception ex)
{
txtStatus.Text = ex.Message;
}
private void ReportException(System.Data.OleDb.OleDbException oleex)
{
StringBuilder sb = new StringBuilder();
sb.Append(oleex.ErrorCode + System.Environment.NewLine);
sb.Append(oleex.Message + System.Environment.NewLine );
txtStatus.Text = sb.ToString();
}
private void ReportMessage(string msg)
{
txtStatus.Text = msg;
}
EDIT
Can you open the file "storekeeper.accdb" in the program "Microsoft Access". It's not password protected is it?
You need put double slash on data source path on your connection string e.g.
'Data Source=C:\folder1\data\Oren.accdb;Persist Security Info=False;";'
Related
Right now, my professor requires me to implement a case study using ADO.NET to save data into SQL Server. I have already created a database and tables in SQL Server and I'm trying to create some forms in Visual Studio by C# ADO.NET. I write according to a YouTube video. But I don't know why I cannot save my data to database successfully.
The result as I write my code like this.
Any help would be appreciated.
namespace casestudy
{
public partial class Form2 : Form
{
SqlConnection vcon2 = new SqlConnection(#"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
vcon2.Open();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
{
string vsql = string.Format("insert into Calluser values ({0}, '{1}', '{2}', {3})", Int32.Parse(txtUserID.Text), txtFName.Text, txtLName.Text, Int32.Parse(txtZoneID.Text));
SqlCommand vCom = new SqlCommand(vsql, vcon2);
try
{
vCom.ExecuteNonQuery();
vCom.Dispose();
MessageBox.Show("The User Information stored.");
txtZoneID.Text = "";
txtLName.Text = "";
txtFName.Text = "";
txtUserID.Text = "";
txtUserID.Focus();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
}
}
Can you add a check to see if the connection is actually open and if not reopen it just before you call the ExecuteNonQuery()
if (vcon2.State != ConnectionState.Open)
{
vcon2.Open();
}
vCom.ExecuteNonQuery();
Opening the connection when the application or form opens is probably not the best approach. You want to open the connection right before you execute your sql and close it as soon as possible.
That being said, I recommend removing the code from the Form2_Load event. And do everything in the button1_Click or another method you call from there. Even better would be to have a class or component that does the data access for your application. Also use a using statement as it will ensure resources are disposed even if an exception is thrown.
using (SqlConnection connection = new SqlConnection(#"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");))
{
SqlCommand command = new SqlCommand(vsql, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
Some info on the using statement:
http://www.dotnetperls.com/using
https://msdn.microsoft.com/en-us/library/yh598w02.aspx
My code is like this : I input the caseid in the textbox and try to click Find button to find the corresponding result. But Visual studio always says :error occored The connection was not closed The connection current state is open.
This is my first time design ADO.NET myself and I need to finish my advisor research tasks.
Could you check the code and tell me what wrong?
Thanks
Sophia
using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace casestudy
{
public partial class Form1 : Form
{
SqlConnection vcon1 = new SqlConnection(#"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
vcon1.Open();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
private void Find_Click(object sender, EventArgs e)
{
string querystring = "SELECT * FROM AssignedSolution WHERE CASEID = #caseid";
SqlCommand Vcom = new SqlCommand(querystring, vcon1);
Vcom.Parameters.AddWithValue("#caseid", txtCASEID);
SqlDataReader rdr = null;
try
{
Vcom.Connection = vcon1;
vcon1.Open();
Vcom.ExecuteNonQuery();
//DataSet vds1 = new DataSet();
rdr = Vcom.ExecuteReader();
//vDa1.Fill(vds1, "res");
//dataGridView1.DataSource = vds1.Tables["res"];
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
Vcom.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
}
finally
{
vcon1.Close();
vcon1.Dispose();
}
}
The connection is being opened on Form1_Load event, then you are trying to open the same connection again in the Find_Click event. You can't open a connection that is already open. Just remove all code from the load event, you don't need it.
I would like to know what's the problem, or your advice to connect to Oracle. I'm trying with this but when I try to insert values, it doesn't work.
I'm using the Visual Web Developer 2008 and when I add a database on Database Explorer connections, it's working. But when I try to connect via this connection string, it doesn't work. What am I missing?
I don't get an exception, so apparently it's working well. But this code apparently doesn't insert! The id column is a varchar(45). I created the table "test" just for testing purposes.
using System.Data;
using System.Data.OracleClient;
public partial class _Default : System.Web.UI.Page
{
//string oradb = "Data Source=localhost;User ID=root;Password=jesua;Unicode=True;";
String oracle = "User ID=root;Password=jesua;Unicode=True;Data Source=localhost;";
OracleConnection con = new OracleConnection();
public void Conectar() {
try
{
con.Close();
con.ConnectionString = oracle;
con.Open();
}
catch(Exception ex){
throw new Exception("No Conecto " + ex);
}
}
public void desconectar() {
// con.ConnectionString = oracle;
con.Close();
}
public void agregar() {
this.Conectar();
OracleCommand query = new OracleCommand("INSERT INTO testing (id) VALUES ('testing')");
query.ExecuteNonQuery();
desconectar();
}
protected void Button1_Click(object sender, EventArgs e)
{
try {
agregar();
}
catch(Exception ex){
Console.Write("No agrego " + ex);
}
TextBox1.Text = "Conected";
}
}
--------------------------UPDATE------------------
So,
i found the way to do that,
i hope anyone here can use this code in a future...
This code creates the connection betwen Oracle and asp.net C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace proyecto
{
public partial class WebForm1 : System.Web.UI.Page
{
public void dbconnect() {
string oradb = "Data Source=localhost;User ID={Yoir ID};Password={Your Password};";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO TESTING(id) VALUES ('valor')";
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
Console.Write("Record not inserted");
else
Console.Write("Success!");
conn.Dispose();
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
this.dbconnect();
}
}
}
Good Luck!
The connection string that works for me is
connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1522))
(CONNECT_DATA=(SERVICE_NAME=XE)));User Id=system;Password=pass;"
providerName="Oracle.DataAccess.Client"/>
It seems that you are missing the Service Name and Provider Name. You can find the service name in tnsnames.ora file which will be in your installation directory. Also make sure you have installed ODP.NET for Oracle 11g correctly, added reference to the Oracle.DataAccess.dll into your project and add the Provider Name in the connection string.
i have a problem with this c# code. I need to connect it to mysql, localhost database, Please give me the correct code to [connetionString = "Data Source=ServerName;Initial Catalog=root;User ID=root;Password="; ] connect to the localhost.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
**connetionString = "Data Source=ServerName;Initial Catalog=localhost;User ID=root;Password=";**
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
It should look a little more like this:
connetionString = "Data Source=localhost;Initial Catalog=<Name of the Database>;User ID=root;Password=";
The data source property is where you put the network location, the initial catalog is the name of the database (in mysql).
Edit:
However, I believe you'll need the mysql libraries, which I notice you're not using at the beginning.
Get them from here: http://dev.mysql.com/downloads/connector/net/
The Data.SqlClient namespace is typically how you'd connect to MSSQL.
it seems you have tagged MySql connection, so preferably you want to use the mysql connection. Which you can download / install here: http://dev.mysql.com/downloads/connector/net/
Also it is wise to use the try-catch-finally approach. So that when the connection opens, and some exception occurs, the connection will always close afterwards.
As another addition, you could put the connectionstring in an App.Config or Web.Config so that you have the connectionstring available in all your files, and only have to adjust it in one place.
hope this will help you
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient; //using the mysql dll
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=localhost;Initial Catalog=myDb;User ID=MyUser;Password=MyPass";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
MessageBox.Show(ex.Message); //shows what error actually occurs
}
finally
{
cnn.Close();
}
}
}
}
You are using System.Data.SqlClient in your connection which I think used for SQL Server. Your connection string is also not for MySQL Database. Try this one.
using System.Data.Odbc;
string connectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost;
DATABASE=dbname; UID=myuserid; PASSWORD=mypassword;OPTION=3; POOLING=false;";
OdbcConnection DBCon = new OdbcConnection(connectionString);
if (DBCon.State == ConnectionState.Open)
{
DBCon.Close();
}
DBCon.Open();
MessageBox.Show ("Connection Open ! ");
DBCon.Close();
Change the ODBC Driver version depending on what you are using.
Change the DATABASE, UID and PASSWORD value.
Here is the code you need
private void btnConnect_Click(object sender, EventArgs e)
{
string MyConStr = "Server=localhost;Database=YourDB;Username=YourUsername;Password=YourPassword";
MySqlConnection conn = new MySqlConnection(MyConStr);
conn.Open();
if (conn.State == ConnectionState.Open)
{
MessageBox.Show("Connection Opened Successfully");
conn.Close();
}
else
{
MessageBox.Show("Error Connecting to DataBase");
}
}
I have created a database using SQL Server Management Studio and am now trying to edit that database using Visual Studio Express 2012. I have connected the database to Visual Studio and can see my database but I have not been able to edit the database stored in Management Studio using Visual Studio. I have created a form and am trying to insert what is entered into textbox1 into a specific cell on my database after the user defines the column name and row (using the primary key in my DB) with textbox2 and textbox3. What code can I use to perform this action? So far I have had no luck. Thank you in advance for you help.
This is my current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
using Microsoft.SqlServer.Server;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection myConnectionString = new SqlConnection("Data Source=Server Catalog=DataBase;Integrated Security=True");
SqlCommand command = new SqlCommand();
private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection dbConnection = new SqlConnection()) // the "using" construct will close and dispose of the connection
{
dbConnection.ConnectionString = ("Data Source=Server ;Initial Catalog=Database;Integrated Security=True");
dbConnection.Open();
maskedTextBox1.Clear();
dateTimePicker1.Value = DateTime.Now.AddDays(0);
comboBox1.SelectedIndex = -1;
String username = comboBox2.Text;
using (SqlCommand command = new SqlCommand("INSERT INTO [Table Name] (Column Name) VALUES ([Parm1])", dbConnection))
{
command.Parameters.AddWithValue("Parm1", username);
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//Close the Window
this.Close();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void comboBox1_DataSourceChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
myConnectionString.Open();
MessageBox.Show("Sql is connected");
myConnectionString.Close();
}
}
}
The VALUES clause should specify a parameter and that parameter should be specified when adding the parameter value. Try substituting the following:
String sqlquery = "INSERT INTO [Man Power] ([Person_Performing_Phase_2]) VALUES ([Parm1])";
SqlCommand command = new SqlCommand(sqlquery, con);
command.Parameters.AddWithValue("Parm1", username);
EDIT
Your connection string is incorrectly formed. I believe the following format is appropriate for your current needs:
String myConnectionString = Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
I would use the following code for inserting data, which opens and closes the connection for each operation. Note the "command.ExecuteNonQuery" statement - its omission is why your insert failed to work - although I am unsure why opening the connection did not throw an error.
private void button3_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection dbConnection = new SqlConnection()) // the "using" construct will close and dispose of the connection
{
dbConnection.ConnectionString = myConnectionString;
dbConnection.Open();
maskedTextBox1.Clear();
dateTimePicker1.Value = DateTime.Now.AddDays(0);
comboBox1.SelectedIndex = -1;
String username = comboBox2.Text;
using (SqlCommand command = new SqlCommand("INSERT INTO [Man Power] ([Person_Performing_Phase_2]) VALUES ([Parm1])", dbConnection))
{
command.Parameters.AddWithValue("Parm1", username);
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
You should also remove all other _Click methods and replace the connection and command statement with the myConnectionString assignement.