Error while trying to use Microsoft.ACE.OLEDB.12.0 - c#

I am trying to read data from an Excel .xlsx spreadsheet and put it into a datagridview.
However when ever I run my code it gives me the following error:
System.InvalidOperationException: 'The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.'
After some googling it looks like its something to do with the version of excel i have installed (I have Office 2019 Pro installed on my machine) but I dont really know how to rectify it. I have tried changing the version number to various things on the "Microsoft.ACE.OLEDB.12.0" bit of my code but with no success. Im not 100% sure how this works, is it my version of Excel installed on my machine that matters or is it some kind of library I should have that I need to get within visual studio?
My code is as follows:
DataTable rs = new DataTable();
using (var odConnection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=c:\myfile.xlsx;Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"))
{
odConnection.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = odConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
using (OleDbDataAdapter oleda = new OleDbDataAdapter(cmd))
{
oleda.Fill(rs);
dataGridView4.DataSource = rs;
dataGridView4.Font = new Font("MS Sans Serif", 8);
}
}
odConnection.Close();
}

The last time I battled with this issue my problem was 32 bit/64 bit, I think you should check that first. Also read the documentation here

Related

Update SQL LocalDB schema in C# WinForms Application through setup

I am creating a C# WinForms Application along with SQL LocalDB. I am new to SQL and I am following this tutorial (timestamp: 5.50) to add database in project. I have also added a setup project to install the application to other PCs. When I installed the project for the first time it worked perfectly well, but when I updated the database schema (added one more column) the changes are not reflecting, updated version of setup & assembly and installed the setup file again, the database schema changes are not reflecting in the application. It is giving the following error:
My code is something like this:
private void load_list()
{
string conn = Properties.Settings.Default.dbAgeConnectionString;
SqlConnection sqlConn = new SqlConnection(conn);
string sqltext = "SELECT Name, Age, DOB from Users";
if (sqlConn.State != ConnectionState.Open) sqlConn.Open();
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqltext,sqlConn);
adapter.Fill(table);
sqlConn.Close();
lstRecords.DisplayMember = "Name";
lstRecords.ValueMember = "Id";
lstRecords.DataSource = table;
gvrecords.DataSource = table;
}
Connection String:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dbAge.mdf;Integrated Security=True
I tried adding the database files manually in Application folder of Setup but still no results.
I searched on the internet but did not find any database version control or upgrade method for SQL LocalDB. Is there any way I can achieve this?
Thanks in advance.

I need to connect with Remote Database from Xamarin application [duplicate]

I'm having trouble with my code to access a MySQL Database. Everytime I try to open my connection, a System.TypeInitializationException is thrown by MySql.Data.MySqlClient.Replication.ReplicationManager. Here is my code:
DataTable results = new DataTable("Results");
using (MySqlConnection connection = new MySqlConnection("SERVER=127.0.0.1;DATABASE=foo;UID=bar;PASSWORD=foobar;"))
{
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
command.Connection.Open(); //throws System.TypeInitializationException
command.ExecuteNonQuery();
using (MySqlDataReader reader = command.ExecuteReader())
results.Load(reader);
}
}
Edit: I guess MySQL Driver was corrupt. After an upgrade from Windows 7 to Windows 10 everything worked fine.
I had the same problem but when i installed the MySql.Data.dll using Nuget then the problem is solved
Install MySql.Dll file from Nuget,
not from MySQL Website.
Your connection string format is wrong. Try this :
static string cs = #"server=localhost;user id=bar;password=foobar;database=foo;";
DataTable results = new DataTable("Results");
using (MySqlConnection connection = new MySqlConnection(cs))
{
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
command.Connection.Open(); //throws System.TypeInitializationException
command.ExecuteNonQuery();
using (MySqlDataReader reader = command.ExecuteReader())
results.Load(reader);
}
}
In my case, it raised error only in production. It was due to a wrong assumption in the MySql.Data package. It for some reason seems to demand to be in the same folder as the orchestrating dll (it was referencing another dll which was referencing MySql). I resolved my issue by removing MySql.Data and instead installing MySqlConnector package as suggested in here.

Unable to connect to database using Oracle.ManagedDataAccess and Windows Native Authentication

I am having trouble connecting to an Oracle database using Oracle.ManagedDataAccess and Windows Native Authentication.
I am developing on a workstation from which I am able to connect to the same database using NTS via the PL/SQL Developer, and via C# code using non-managed Oracle.DataAccess. This leads me to I believe that there is nothing fundamentally wrong with either the database, workstation or the account. Now I am trying to evaluate if it's possible to switch to Oracle.ManagedDataAccess in our solution.
I've tried the following so far:
Created a new blank project OracleManagedAccessTest
Under references added the NuGet package Oracle.ManagedAccessTest v19.3.1 (the latest at the time of writing)
Update the <dataSource> tag in the App.config to match the entry in the tnsnames.ora (to make the C# project self-contained and not relying on external component)
Added <setting name="sqlnet.authentication_services" value="NTS"/> tag under <oracle.manageddataaccess.client><version number="*"><settings> in the App.config
I am using the following minimal code to test the connection:
try
{
using (OracleConnection conn = new OracleConnection("Data Source=EDBDEVD;User Id=/;"))
{
conn.Open();
}
}
catch (OracleException ex)
{
Console.WriteLine("Exception Message: " + ex.Message);
}
The attempt to connect fails with the following error: "ORA-01017: invalid username/password; logon denied"
This looks almost like too simple of a problem, yet I can't seem to resolve it, or find a workable solution online. Any help would be greatly appreciated.
Try this one:
string oradb = "Data Source=ORCL;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select department_name from departments where department_id = 10"; cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
label1.Text = dr.GetString(0);
see also: https://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/GettingStartedNETVersion/GettingStartedNETVersion.htm

SQLite.Interop.DLL How to use non managed DLL

I would like to use System.Data.SQLite with an wpf application.
So I dowloaded the files here and add the reference to System.Data.SQLite downloaded.
Then I write the code
SQLiteConnection connex = new SQLiteConnection(#"Data Source=C:\Users\Toto\Desktop\Test.sqlite;");
connex.Open();
DataTable dt = new DataTable();
SQLiteCommand command = connex.CreateCommand();
command.CommandText = "SELECT * FROM TEST";
SQLiteDataAdapter da = new SQLiteDataAdapter();
da.SelectCommand = command;
da.Fill(dt);
connex.Close();
But It doesn't work.. When I try to open the connexion, it says that it is impossible to find the SQLite.Interop.dll.. No problem I have this one but impossible to add reference to it because it is an unmanaged DLL.
So, if someone is used to use SQLite and ADO.NET I'm looking for advices..
Thanks a lot
You just need to copy the unmanaged DLL to the same folder as your EXE.

What is the best way to connect and use a sqlite database from C#

I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?
I'm with, Bruce. I AM using http://system.data.sqlite.org/ with great success as well. Here's a simple class example that I created:
using System;
using System.Text;
using System.Data;
using System.Data.SQLite;
namespace MySqlLite
{
class DataClass
{
private SQLiteConnection sqlite;
public DataClass()
{
//This part killed me in the beginning. I was specifying "DataSource"
//instead of "Data Source"
sqlite = new SQLiteConnection("Data Source=/path/to/file.db");
}
public DataTable selectQuery(string query)
{
SQLiteDataAdapter ad;
DataTable dt = new DataTable();
try
{
SQLiteCommand cmd;
sqlite.Open(); //Initiate connection to the db
cmd = sqlite.CreateCommand();
cmd.CommandText = query; //set the passed query
ad = new SQLiteDataAdapter(cmd);
ad.Fill(dt); //fill the datasource
}
catch(SQLiteException ex)
{
//Add your exception code here.
}
sqlite.Close();
return dt;
}
}
There is also an NuGet package: System.Data.SQLite available.
Microsoft.Data.Sqlite by Microsoft has over 9000 downloads every day, so I think you are safe using that one.
Example usage from the documentation:
using (var connection = new SqliteConnection("Data Source=hello.db"))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText =
#"
SELECT name
FROM user
WHERE id = $id
";
command.Parameters.AddWithValue("$id", id);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var name = reader.GetString(0);
Console.WriteLine($"Hello, {name}!");
}
}
}
I've used this with great success:
http://system.data.sqlite.org/
Free with no restrictions.
(Note from review: Original site no longer exists. The above link has a link pointing the the 404 site and has all the info of the original)
--Bruce
There is a list of Sqlite wrappers for .Net at http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers. From what I've heard http://sqlite.phxsoftware.com/ is quite good. This particular one lets you access Sqlite through ADO.Net just like any other database.
There's also now this option: http://code.google.com/p/csharp-sqlite/ - a complete port of SQLite to C#.
https://github.com/praeclarum/sqlite-net is now probably the best option.
Another way of using SQLite database in NET Framework is to use Fluent-NHibernate.
[It is NET module which wraps around NHibernate (ORM module - Object Relational Mapping) and allows to configure NHibernate programmatically (without XML files) with the fluent pattern.]
Here is the brief 'Getting started' description how to do this in C# step by step:
https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started
It includes a source code as an Visual Studio project.
Here I am trying to help you do the job step by step: (this may be the answer to other questions)
Go to this address , down the page you can see something like "List of Release Packages". Based on your system and .net framework version choose the right one for you. for example if your want to use .NET Framework 4.6 on a 64-bit Windows, choose this version and download it.
Then install the file somewhere on your hard drive, just like any other software.
Open Visual studio and your project. Then in solution explorer, right-click on "References" and choose "add Reference...".
Click the browse button and choose where you install the previous file and go to .../bin/System.Data.SQLite.dll and click add and then OK buttons.
that is pretty much it. now you can use SQLite in your project.
to use it in your project on the code level you may use this below example code:
make a connection string:
string connectionString = #"URI=file:{the location of your sqlite database}";
establish a sqlite connection:
SQLiteConnection theConnection = new SQLiteConnection(connectionString );
open the connection:
theConnection.Open();
create a sqlite command:
SQLiteCommand cmd = new SQLiteCommand(theConnection);
Make a command text, or better said your SQLite statement:
cmd.CommandText = "INSERT INTO table_name(col1, col2) VALUES(val1, val2)";
Execute the command
cmd.ExecuteNonQuery();
that is it.
Mono comes with a wrapper, use theirs!
https://github.com/mono/mono/tree/master/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0 gives code to wrap the actual SQLite dll ( http://www.sqlite.org/sqlite-shell-win32-x86-3071300.zip found on the download page http://www.sqlite.org/download.html/ ) in a .net friendly way. It works on Linux or Windows.
This seems the thinnest of all worlds, minimizing your dependence on third party libraries. If I had to do this project from scratch, this is the way I would do it.
if you have any problem with the library you can use Microsoft.Data.Sqlite;
public static DataTable GetData(string connectionString, string query)
{
DataTable dt = new DataTable();
Microsoft.Data.Sqlite.SqliteConnection connection;
Microsoft.Data.Sqlite.SqliteCommand command;
connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source= YOU_PATH_BD.sqlite");
try
{
connection.Open();
command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection);
dt.Load(command.ExecuteReader());
connection.Close();
}
catch
{
}
return dt;
}
you can add NuGet Package Microsoft.Data.Sqlite

Categories

Resources