I'm trying to create a very simple webshop in Razor with SQLite. Unfortunately, when i trying to create the database (or creating the SQLiteConnection object) it throws a strange System.BadImageFormatException.
An attempt was made to load a program with an incorrect format.
(Exception from HRESULT: 0x8007000B)"} System.BadImageFormatException
My code looks similar as the following:
public bool CreateDatabase()
{
try
{
string db = HttpContext.Current.Server.MapPath("~/App_Data/mydb.sqlite");
SQLiteConnection.CreateFile(db);
SQLiteConnection m_dbConnection = new SQLiteConnection(#"Data Source="+ db + ";Version=3;");
m_dbConnection.Open();
string sql = "create TABLE cart (UserHash varchar(35), imageid varchar(255), rider varchar(255), competition varchar(255), usagetype varchar(255), retouch varchar(10), blacknwhite varchar(10))";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
return true;
}
catch (Exception)
{
return false;
}
}
This website probably will run on third-party hosting, so it's essential to use a relative path for the sqlite file location, although i couldn't get it work so far.
In db variable, i get the correct App_Data folder location.
I get the exception at new SQLiteConnection. I also tried using the following connectionstring, no luck:
"Data Source=|DataDirectory|mydb.sqlite; Version=3;"
What am i missing?
BadImageFormatException happens when your application and your libraries use a different bitness. For example, the application is built for AnyCPU (without prefer 32bit) or x64 and your libraries are compiled for 32bit or viceversa.
Usually the solution is very simple. Just copy the appropriate version of SQLite for the bitness of your app to your run folder or change the Target Platform of your app to match the library version used
I need to use .net standard 2.0 for my database component. This component uses the Microsoft package Microsoft.Data.Sqlite for access. That seems to work but how can I create a database file? Are there any other packages I may use for accessing Sqlite under a .net standard 2.0 component?
Best regards,
Torsten
Following works:
using (var connection = new SqliteConnection("" + new SqliteConnectionStringBuilder
{
DataSource = "C:\\temp\\test.db"
}))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "create table test(field1 varchar(20))";
command.ExecuteNonQuery();
}
}
It is created by default, there is no explicit create file or anything like this.
I use SQLite for Windows Runtime (Windows 8.1) and SQLite.Net-PCL extension.
I work with databases in user local folder. Path to this folder contains username. So, sometimes it may contain special characters (e.g. 'ลก').
It works correctly when I create connection and open a database. However, the problem occurred when trying to attach another database. I always got exception "CannotOpen".
I suppose the problem is based on different encoding (UTF-8 in SQLite, UTF-16 in .Net) but I haven't managed to resolve it.
Sqlite contains methods for opening database in UTF 16 (sqlite3_open16). But there is no such a method for SQL statements.
string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "sqlite1.db");
string dbPath2 = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "sqlite2.db");
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLitePlatformWinRT(), dbPath))
{
var cmd = conn.CreateCommand("ATTACH '" + dbPath2 + "' AS second;");
cmd.ExecuteNonQuery(); // -> it throws "CannotOpen" exception if dbPath2 contains special characters
}
Thanks for your help!
I'm trying to write a C# console application that interacts with a sqlite DataBase. Every time I try to build my console application project, an empty SuperCrewNet.sqlite file is being created in my Bin folder and causes the "Flights" table (and all other tables) to disappear, the original sqlite file next to the main cs file id perfectly fine.
When I try to the sqlite_cmd.ExecuteScalar(), an exeption is thrown (no such table: Flights)
How do I solve this problem??
sqlite_conn = new SQLiteConnection("Data Source=SuperCrewNet.sqlite;Version=3;New=True;Compress=True;");
sqlite_conn.Open();
sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd.CommandText = "SELECT FlightID FROM Flights WHERE FlightID='" + FlightNumber + FlightDate + "'";
sqliteDatareader = sqlite_cmd.ExecuteScalar();
Check this site for help on connection strings:
http://www.connectionstrings.com/sqlite/
As mentioned in comments:
Create a new database:
Data Source=c:\mydb.db;Version=3;New=True;
So just remove New=True;
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