SQLite.Interop.DLL How to use non managed DLL - c#

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.

Related

Error while trying to use Microsoft.ACE.OLEDB.12.0

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

Using MySql.Data with C# while not making a MySqlConnection

The reccomended way to use MySql.Data is to NOT use a MySqlConnection object; as explained in the documentation. This allows for the MySQl.Data API code to handle connection pooling correctly.
See: mySQL documentation
So, for example, this code Selects data with the connection string passed in as a parameter.
The MySqlConnection object is created in the background:
DataSet dataset = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter("select * from cfx_jobs", _mySqlConnectionString);
adapter.Fill(dataset);
return dataset;
I have looked around and I cannot find an example of how to Insert into the database without explicitly creating a MySqlConnection object.
Which method should I use?
This is how to do it.
MySqlHelper.ExecuteNonQuery(_mySqlConnectionString, sqlStatement);

TypeInitializationException C# using mysql connection

I have a web C# app, all tables were created on MSSQL Server, I need to use some data now on another server which uses MySql. I may overcome my problem with a simple web service, but I wanted to add MySql just for learning. Here is the code.
MySqlConnection con = new MySqlConnection("server=10.45..;user id=user;persistsecurityinfo=True;database=db;password=pass");
MySqlCommand cmd = new MySqlCommand("select * from izin", con);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds); **//typeinitializationexception was unhandled by user code**
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
cmd.Dispose();
I get TypeInitializationException was unhandled by user code error from adapter. I couldn't find any similar problem.
I found the solution.
You need to add a new user with sql codes. I added mine from menus and it sure doesn't work.
Here is the code.
GRANT ALL PRIVILEGES ON *.* TO 'root'#'192.168.1.%'
IDENTIFIED BY 'some_characters'
WITH GRANT OPTION;
FLUSH PRIVILEGES;

Update database using SqlCeDataAdaptor

I populate a listview from a Dataset that accesses sqlserver in visual studio 2008 express edition. I've been trying to update the listview and database simultaneously.
SettingTxt.Text references a textbox
With the following code, I've been able to update the list view with the information entered into the textbox, but the same update is not performed in the database. If anyone can help me resolve this, I would greatly appreciate it. I know there are alot of forums online regarding this exact problem, but I can't seem to get it working.
thisConnection = new SqlCeConnection("Data Source=AugMedDB.sdf;Password=");
thisConnection.Open();
SqlCeCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = "UPDATE Patient SET Setting = \'" + SettingTxt.Text + "\' WHERE (PtID=0) AND (EquipID=1) AND (Control='Lever')" ;
SqlCeDataAdapter adp = new SqlCeDataAdapter();
adp.UpdateCommand = cmd;
dataSet.Tables[0].Rows[0][2] = SettingTxt.Text;
adp.Update(dataSet);
Thanks in advance.
Moved from an answer:
What I currently have is:
SqlCeCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = "SELECT column FROM table WHERE id=0";
SqlCeDataAdapter adp = new SqlCeDataAdapter(cmd);
adp.SelectCommand = cmd;
DataSet ds = new DataSet();
ds = dataS.getDataSet();
adp.Fill(ds, "Patient");
SqlCeCommand comm = thisConnection.CreateCommand();
comm.CommandText = "UPDATE table SET Setting = 'value' WHERE (PtID=0)";
adp.UpdateCommand = comm;
adp.Update(ds, "Patient");
And I'm not understanding all the tutorials I find. Thanks in advance.
Update:
Yet even something as simple as the following doesn't update the database:
SqlCeConnection thisConn = new SqlCeConnection("Data Source=AugMedDB.sdf;Password=");
String query = "UPDATE Patient SET Setting = 'TopyTruck' WHERE (PtID=0) AND (EquipID=1) AND (Control='Lever')";
thisConn.Open();
SqlCeCommand commd = new SqlCeCommand(query, thisConn);
commd.ExecuteNonQuery();
thisConn.Close();
Your UPDATE statement is not suitable for an Adapter.Update(), for that it needs parameters and must be aligned with the SELECT statement.
You could try to execute that Command directly (w/o the adapter) or create a better update statement (using the dataset designer ).
Update
After filling the dataset,
generate the other SQL statements with a CommandBuilder (I think it exists for SqlCe)
or use your use your own Update command without the adapter. Just call comm.ExecuteNonQuery()
Tip 1: It may help to create a temporary (WinForms) project and use the VS tools to "Add a Datasource". You can look in the Dataset designer how VS generates the commands etc.
Tip 2: There are other options available, like entity framework. Datasets are (becoming) an "end of life" tech.
Thank you so much for all your help. I actually found the source of the problem. I had multiple references to the database; one within my project and another copy in bin/debug. I was correctly updating the copy in bin/debug but I was looking at the copy in my project. Once I deleted all copies, other than the one in bin/debug, it all worked and made sense. Now I see the updates in the database in bin/debug/

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