Microsoft Access 2007 Database Connection in Visual Studio 2010 - c#

I am new in creating application in Visual Studio 2010. I recently created an application which has a MySQL as a database. Now, I am creating an app where I used a MS Access 2007 as a database.
I have this code for the database connection of MySQL:
class DBConn
{
string MyConString = "SERVER=localhost;" + "DATABASE=payroll;" + "UID=root;" + "PASSWORD=admin;";
public DataTable retrieveRecord(string cmd)
{
MySqlConnection con = new MySqlConnection(MyConString);
MySqlCommand command = new MySqlCommand(cmd, con);
MySqlDataAdapter adp = new MySqlDataAdapter(command);
con.Open();
DataSet set = new DataSet();
adp.Fill(set);
con.Close();
return set.Tables[0];
}
}
My problem now is that how to change this code to access the database of MS Access 2007? Please help. Thanks.

Change the connection string to something like this: "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\yourdatabase.mdb;User Id=username;Password=password;"

Related

Error when trying to load Excel information

I have C# WinForms application that gets information from Excel sheet and stores it to my database, my code works fine on my PC but when I changed it an Error
System.InvalidOperationException: 'The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.'
display. I solved this problem by changing the project platform from x86 to x64 but when I launch the project with x64 I can't charge many files so I have to run it on x86. Guys any solutions?
Rq: My code:
String name = "Feuil1";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
textBox_path.Text +
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataview1.DataSource = data;
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["UR2k_CS.Properties.Settings.StoreConnectionString"].ConnectionString))
{
String query = "INSERT INTO dbo.Stock (RFID,name,refrence,prix,Stockdate) VALUES (#RFID,#name,#refrence,#prix,#Stockdate)";
connection.Open();
for (int i=0;i<dataview1.Rows.Count-1;i++)
{
using (SqlCommand command = new SqlCommand(query, connection))
{
if ((dataview1.Rows[i].Cells[0].Value.ToString()!=null)&&((!checkifexist(dataview1.Rows[i].Cells[0].Value.ToString()))) &&(dataview1.Rows[i].Cells[0].Value.ToString()!=""))
{
command.Parameters.AddWithValue("#RFID", dataview1.Rows[i].Cells[0].Value.ToString());
command.Parameters.AddWithValue("#name", dataview1.Rows[i].Cells[1].Value.ToString());
command.Parameters.AddWithValue("#refrence", dataview1.Rows[i].Cells[2].Value.ToString());
command.Parameters.AddWithValue("#prix", dataview1.Rows[i].Cells[3].Value.ToString());
command.Parameters.AddWithValue("#Stockdate", DateTime.Now);
command.ExecuteNonQuery();
}
}
}
connection.Close();
}
You need to download the 32 bit driver from here microsoft downloads (I think this is the correct one) but the difficulty you may run into is that a machine cannot have both the 64bit and 32bit versions installed side by side.
Using EPPlus is a more modern approach.

Create Table query with SQL Server CE

Which is the best way to execute a query in C# + SQL Server CE? I need to create a table, but after 3 days of unsuccessful attempts, I realize that I really can't do it for myself... So I'm here asking for help.
I've tried these topics:
create sql table programmatically
Data Adapter Vs Sql Command
But all ways I tried show me an exception... I'm confused, where is my mistake?
My current code:
public void Connect()
{
try
{
string FileName = "DataBase";
using (SqlCeConnection myConnection = new SqlCeConnection(#"Data Source=|DataDirectory|\" + FileName + ".sdf;Password=Z123"))
{
string query = "create table EXP(ID int, source int)";
int i;
SqlCommand cmd = new SqlCommand(query, connection);
cmd.con.open();
i = cmd.ExecuteNonQuery();
}
}
catch (SqlCeException ae)
{
MessageBox.Show(ae.Message.ToString());
}
}
Many thanks!
If you're using SQL Server CE then you need to use a SqlCeCommand (not a SqlCommand - that's for the full-blown SQL Server).
So change your code to:
using (SqlCeConnection myConnection = new SqlCeConnection(#"Data Source=|DataDirectory|\" + FileName + ".sdf;Password=Z123"))
{
string query = "create table EXP(ID int, source int)";
// use SqlCeCommand here!! Also: use the "myConnection" SqlCeConnection you're
// opening at the top - don't use something else.....
SqlCeCommand cmd = new SqlCeCommand(query, myConnection);
myConnection.open();
cmd.ExecuteNonQuery();
myConnection.Close();
}

Track Database Status Change sql server

I want to Track database status changed in sql server . in my solution ,I have a database that is offline due to restore from primary server .
i want to get hint in my application(C#) when database is offline and when is online. (like sql notification event) .
Thanks .
One way is to check the state of the database using a timer from your application
private void timer1_tick(object sender,EventArgs e)
{
if(CheckDatabaseState() == "ONLINE")
MessageBox.Show("db is online");
else
MessageBox.Show("db is NOT online");
}
Public string CheckDatabaseState()
{
string Constr = #"Data Source=.\SQLEXPRESS;Integrated Security=True;Initial Catalog=master;";
string sql = string.Format("SELECT Name, state_desc FROM sys.databases where name = '{0}'", dbName);
SqlConnection conn;
SqlCommand comm;
SqlDataAdapter adapter;
DataSet ds = new DataSet();
conn = new SqlConnection(Constr);
comm = new SqlCommand(sql, conn);
adapter = new SqlDataAdapter(comm);
adapter.Fill(ds);
return ds.Tables[0]["state_desc"].ToString();
}
Let me know if this helps,

Get data in a .dbf file using c#

How can I get the data in a .dbf file using c#??
What I want to do is to read the data in each row (same column) to further process them.
Thanks.
You may create a connection string to dbf file, then using OleDb, you can populate a dataset, something like:
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=directoryPath;Extended Properties=dBASE IV;User ID=Admin;Password=;";
using (OleDbConnection con = new OleDbConnection(constr))
{
var sql = "select * from " + fileName;
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
DataSet ds = new DataSet(); ;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
}
Later you can use the ds.Tables[0] for further processing.
You may also check this article Load a DBF into a DataTable
I found out the accepted answer didn't work for me, as the .dbf files I'm working with are nested in a hierarchy of directories that makes the paths rather long, which, sadly, cause the OleDbCommand object to throw.
I found a neat little library that only needs a file path to work. Here's a little sample adapted from the examples on its GitHub page:
var file = "C:\\Path\\To\\File.dbf";
using (var dbfDataReader = new DbfDataReader(file))
{
while (dbfDataReader.Read())
{
var foo = Convert.ToString(dbfDataReader["FOO"]);
var bar = Convert.ToInt32(dbfDataReader["BAR"]);
}
}
For 64 bit systems I used the Microsoft ACE OLEDB 12.0 data provider, for that provider to work you have to install Microsoft's Access Database Engine 2010
So it looks a lot like the accepted answer but with the provider changed:
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\folder;Extended Properties=dBASE IV;User ID=Admin;";
using (OleDbConnection con = new OleDbConnection(constr))
{
var sql = "select * from " + fileName;
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
}

how to use oracle dbms_utility in c#

I want to use ORACLE DBMS feature in my C# application to compile all the invalid objects but I received below error. would you please help me how I can run below script in C#:
"exec dbms_utility.compile_schema('"+schema+"');";
my function :
internal void compileAllInvalideObject(string userId, string password, string schema)
{
//OracleConnection con = new OracleConnection();
string connectionString = "provider=MSDAORA;data source="+userId+";user id="+userId+";password="+password;
OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
myOleDbCommand.CommandText = "exec dbms_utility.compile_schema('"+schema+"');";
myOleDbConnection.Open();
myOleDbCommand.ExecuteNonQuery();
myOleDbConnection.Close();
}
error:
ORA-00900: invalid SQL statement
I am using oracle 9i.
Actually dbms_utility.compile_schema act same as store procedure so we can not call it in same way which we run a query, we need to write program in such way we call a store procedure.
OracleConnection con = new OracleConnection();
//using connection string attributes to connect to Oracle Database
con.ConnectionString = "User Id="+userId+";Password="+password+";Data Source="+schema;
OracleCommand ocb = new OracleCommand("dbms_utility.compile_schema", con);
ocb.CommandType = CommandType.StoredProcedure;
ocb.Parameters.Add(new OracleParameter("#schema", userId));
con.Open();
ocb.ExecuteNonQuery();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
// Close and Dispose OracleConnection object
con.Close();
con.Dispose();
Console.WriteLine("Disconnected");

Categories

Resources