C# how to connect WPF and SQLITE database easiest way - c#

New to wpf and sqlite. I just want an internal database for my project. I want this project to be able to used by others so I cannot use mysql as a database. So I search for internal databases and decided to try sqlite. Im finding tutorial but they are really confusing. I'm familiar in database I know the queries but now I just need to know what are the necessary things to setup to start the connection between WPF and sqlite. Below is my code(I create a different class for my sqlite connection):
sqlite class
using System.Data.SQLite;
namespace StartMyApps
{
class StartMyAppDb_sqlite
{
public SQLiteConnection myConn;
public SQLiteCommand myComm;
public SQLiteDataReader myReader;
public void openConnection(string query)
{
myConn = new SQLiteConnection("Data Source=StartMyApplication.sqlite;Version=3;");
myConn.Open();
myComm = new SQLiteCommand(query, myConn);
myComm.ExecuteNonQuery();
myReader = myComm.ExecuteReader();
}
}
}
Main class (has a button to trigger the connection and will pass a query)
private void hide_btn_Click(object sender, RoutedEventArgs e)
{
sqliteDB.openConnection("select *from application where app_id='1' and app_name='chrome.exe';");
bool hasAccount = false;
while (sqliteDB.myReader.Read())
{
hasAccount = true;
}
if (hasAccount == false)
{
MessageBox.Show("Logged in");
}
else if (hasAccount == true)
{
MessageBox.Show("Username invalid");
}
}
With this code I got an error says
"An unhandled exception of type 'System.DllNotFoundException' occurred
in System.Data.SQLite.dll Additional information: Unable to load DLL
'SQLite.Interop.dll': The specified module could not be found.
(Exception from HRESULT: 0x8007007E)"
Please help. Any help will be much appreciated THANKS!

I think this is what your looking for: Unable to load DLL 'SQLite.Interop.dll'
Assuming you have:
SQLite installed (correct version for windows)
Appropriate references

Follow below steps:
Add 2 folders in the project and name it x64 and x86.
Add SQLite.interop.dll for x64 and x86 respectively(google for the same)
In SQLite.interop.dll properties, set
"Build Action" --> Content
and "Copy to Output directory" -> Copy Always/Copy if newer.

Related

How can I change my SQLite connection string at runtime?

I'm working on a small project that's unrelated to this, it needs a database to be integrated into it, so I looked into SQLite and tried to teach myself the basics.
My code works fine but I realised if I was to deploy this on another machine it wouldn't be able to connect to the database because it wouldn't have the file as I've hard coded it in (it's running of my C:\ drive currently which will be an issue for users who haven't got it there obviously).
I was wondering if it was possible to update to connection string for the user at runtime? Even say, when the user installs it, it installs a copy of the database and changes its path to that?
Here's my code:
using System;
using System.Windows.Forms;
using System.Data.SQLite;
namespace sqltest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string cs = #"Data Source=c:\student.db;Version=3;FailIfMissing=False";
string stm = "SELECT Name FROM Customer";
using var con = new SQLiteConnection(cs);
con.Open();
using var cmd = new SQLiteCommand(stm, con);
using SQLiteDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
MessageBox.Show($"{rdr.GetString(0)}");
}
}
}
}
Thanks for any help!
you can get datasource from config file, e.g. appsetting.json
The connection string that you pass to new SQLiteConnection(...); is actually being passed at runtime already.
Sounds like the simplest solution is to create the database if it doesn't already exists with a predetermined path. This will ensure that when your script runs on a machine that doesn't have a DB, the DB will be created at runtime.
Here's a relevant post: Programmatically create sqlite db if it doesn't exist?

Unable to Load DLL 'sqlite.interop.dll' After Create Setup File

I am working on a windows application using Visual studio 2015(Professional) and Sqlite DataBase, windows 8.1(x64). i Install Sqlite From Nuget it Autometically install These References... system.componentmodel.dataannotations, System.Data.SQLite, System.Data.SQLite.EF6, System.Data.SQLite.Linq .
when i execute my app in visual Studio, Everything is working Fine. then Publish it by Windows Setup. then Install The Newly Created Setup File on My machine windows 8.1(x64). Whenever i try to Run it and Click on Login Button it gives the following error
"unable to load dll 'sqlite.interop.dll': the specified module could not be found. (exception from hresult: 0x8007007e)".
my Code is...
string connectionString = #"Data Source = SampelTest.db; Version = 3; new = false; compress = true; ";
private void buttonLogin_Click(object sender, EventArgs e)
{
using (SQLiteConnection con = new SQLiteConnection(connectionString))
{
try
{
using (SQLiteCommand sqlcmd = new SQLiteCommand("select count(*) from [SampelTest]", con))
{
con.Open();
Int32 count = Convert.ToInt32(sqlcmd.ExecuteScalar());
con.Close();
if (count > 0)
{
MessageBox.Show("User have in DataBase");
}
else
{
MessageBox.Show("Empty DataBase");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
}
My Database file in the Debug Folder "SampelTest.db"i already tried these step that are from Google to resolve my problem.
Coppy Sqlite.Interop.dll File From x64 To Debug Folder.
create x86 and x64 folder from solution Explorar and add Sqlite.Interop.dll from x86 and x64 respectively and Set Property, Build Option => Content, Copy to output Directory => Copy always.
Unchake the Prefer 32-bit.
After Try these steps can't able to solve this problem. Please Help to me to solve this. Thanks For Looking.

MySql from VS 2017 Unable to create Entity Models from database

I am unable to create Entity Models from database.
It is first time using MySQL from VS2017.
I am following tutorial at
1) https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-intro.html
2) https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-entity-framework-winform-data-source.html
3) https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework60.html
I installed MySQL on local machine. I installed NuGet packages MySql.Data, MySql.Data.Entity, and MySql.Web (all version 6.9.11).
In tutorial No.2, while adding “ADO.Net Entity Data Model”, I get upto this window
I click next and then window silently close without producing any Data Models.
This means I don’t see the window below.
I assume my connection strting and web.config file is OK as I can successfully execute code bellow and get result “Samoa -- Malietoa Tanumafili II”
`
using System;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
public class Tutorial2
{
public static void Main()
{
string connStr = "server=localhost;user=root;database=world;port=3306;password=******";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent='Oceania'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]+" -- "+rdr[1]);
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
Console.WriteLine("Done.");
}
}`
Please guide what I am doing wrong.
This is a known bug in MySQL Connector/NET: bug 89338. According to that bug report, there's a bug in the wizard code that should be fixed in the next version, 6.10.7.

Error while doing writing unit test case -Could not load file or assembly 'Oracle.DataAccess, Version=4.112.4.0

We have a requirement to do unit testing using either MS Test or NUnit Framework for our C# code. There are many methods which includes DB call. When trying to do so, I am getting below error:
*{"Could not load file or assembly 'Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=*******' or one of its dependencies. An attempt was made to load a program with an incorrect format."}*
I checked the Oracle version to make sure there is no mismatch, but no success. Also read couple of articles that instead of making DB call one should be using mocking to bypass DB. But with this limitation the coverage is very minimal.
Could anyone please guide to fix the above error. Adding the sample code which i tried just for POC
public class Class1
{
public IEnumerable<ModelClass> GetListOfExceptions()
{
OracleConnection conn = new OracleConnection(Constants.ConnectionString);
try
{
conn.Open();
OracleCommand cmd = new OracleCommand(Constants.<Oracle Query>, conn);
cmd.CommandType = CommandType.Text;
//cmd.CommandType = CommandType.StoredProcedure;
OracleDataReader dr = cmd.ExecuteReader();
ModelClass modelException = null;
List<ModelClass> lst = new List<ModelClass>();
while (dr.Read())
{
modelException = new ModelClass();
modelException.POLICYNO = Convert.ToString(dr.GetValue(1));
modelException.PREMIUM = Convert.ToInt32(dr.GetValue(2));
modelException.AGE = Convert.ToInt32(dr.GetValue(3));
lst.Add(princeException);
}
return lst;
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}
}
}
[TestFixture]
public class Class1Tests
{
[Test]
public void GetListOfExceptionsTest()
{
Class1 obj = new Class1();
obj.GetListOfExceptions();
}
}
Most likely the ODP.NET (i.e. Oracle.DataAccess) is not installed on your machine. Or maybe it is installed but you did not install any Oracle Client (e.g. Oracle Instant Client)
Go to this page Oracle Data Access Components - .NET Downloads and download and install the Oracle Data Provider for .NET. Ensure that you download the same version as your Oracle Client in case you installed already one. Ensure also that you have the same architecture, i.e. 32-bit vs. 64-bit as your application.
Finally the issue is fixed after installation to Oracle Client 12.1 (32 bit version).

How to connect an oracle database in C #?

Since monday I followed several tutorials to establish connection to my Oracle database.
I downloaded at http://www.oracle.com/technetwork/database/windows/downloads/index-090165.html
and launched "install.bat".
In visual studio, in reference section I browsed the directory that I downloaded and found "Oracle.DataAccess.dll" in the following path "\odp.net4\odp.net\bin\4".
When I run my code I get the following error:
External component has thrown an exception
Furthermore I have the following warning :
Warning 1 There is a difference between the project processor
architecture being generated "MSIL" and the reference processor
architecture "Oracle.DataAccess, Version = 4.121.2.0, Culture =
neutral, PublicKeyToken = 89b483f429c47342, processorArchitecture =
x86 "," AMD64 ". This difference can lead to runtime problems.
I don't understand this error so I hope you will be able to help me.
Or if you know a better way to connect to a database oracle, I will be interested.
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OraTest oraTest = new OraTest();
oraTest.Connect();
oraTest.Close();
MessageBox.Show("Connecté");
}
}
}
using Oracle.DataAccess.Client;
namespace WindowsFormsApplication2
{
class OraTest
{
OracleConnection con;
public void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
public void Close()
{
con.Close();
con.Dispose();
}
}
}
I suggest to use Official Oracle ODP.NET
In Nuget type:
Install-Package Oracle.ManagedDataAccess

Categories