access sqlite from .net standard 2.0 - c#

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.

Related

.Net Core - SQL Server Geography data type exception

I am trying to use the new Microsoft.Data.SqlClient in my .Net Core application. Whenever I select a column that has a datatype of Geography, I get the following error.
Unable to cast object of type 'Microsoft.SqlServer.Types.SqlGeography' to type 'Microsoft.Data.SqlClient.Server.IBinarySerialize'.'
To reproduce, I created a database on my computer (SQL2019) with one table:
DROP TABLE IF EXISTS geotest
GO
CREATE TABLE geotest (g GEOGRAPHY)
GO
INSERT INTO geotest (g)
VALUES
( 0xe6100000010cec51b81e854b4040ec51b81e852b58c0 ),
( 0xe6100000010c6666666666a64740713d0ad7a3905ec0 )
I create a console application project (Visual Studio 2019, .Net Core 3.1) and add the NUGET package: Microsoft.Data.SqlClient
Here is my sample app:
using System;
using Microsoft.Data.SqlClient;
namespace TestWithOtherSQL
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=joe;Trusted_Connection=True;");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = #"SELECT g FROM geotest";
SqlDataReader sr = cmd.ExecuteReader();
while (sr.Read())
{
var a = sr[0];
}
conn.Close();
Console.WriteLine("Hello World!");
}
}
}
It throws the error on this line:
var a = sr[0];
Unable to cast object of type 'Microsoft.SqlServer.Types.SqlGeography' to type 'Microsoft.Data.SqlClient.Server.IBinarySerialize'.'
Troubleshooting:
If I change out the Nuget package to System.Data.SqlClient and include package Microsoft.SqlServer.Types (change the using to System.Data.SqlClient) The same code works.
So why don't I just do that? Good question... My actual database is on Azure SQL DB and I need to use Microsoft.Data.SqlClient to support ActiveDirectory Password Authentication (that does not work with System.Data.SqlClient) - but that's a different issue....
Also Microsoft.Data.SqlClient is the "new" ".NetCore" way of doing things. Not a huge issue for me right now, but not sure if that would work if we ported to Linux are tried to run in an Azure function.

How to connect postgreSQL DB with ASP .NET MVC project

I have a problem with connection to database in my .NET ASP application. Maybe has something wrong with App.config or Web.config.
It was connected to MSSQL by default but I have tried connect it to PostgreSQL by npgsql nuget package and entity framework.
It don't even see Database Server for PostgreSQL when I want to create Migration in my project in Visual Studio ( Enable-Migrations; Add-Migration Initial; Update-database).
Here are github links of my code:
webconfig
App.config
I want to know how make it right and make it work proprely.
using System;
using Npgsql; // Npgsql .NET Data Provider for PostgreSQL
class Sample
{
static void Main(string[] args)
{
// Specify connection options and open an connection
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres;" +
"Password=pwd;Database=postgres;");
conn.Open();
// Define a query
NpgsqlCommand cmd = new NpgsqlCommand("select city from cities", conn);
// Execute a query
NpgsqlDataReader dr = cmd.ExecuteReader();
// Read all rows and output the first column in each row
while (dr.Read())
Console.Write("{0}\n", dr[0]);
// Close connection
conn.Close();
}
}

Retrieve custom table data with Azure SQL

I have an Azure Web Site, using a free Azure SQL database, and I have installed Umbraco CMS 7.1.1 to develop the site with. I have also created a custom table using Azure's SQL Management feature and I have created a couple of test rows with dummy text. How can I connect to my custom table and display the data on a page?
Usually I work with MySQL and fetching data is relatively easy to do but I'm having trouble converting my code to work with Azure SQL. The following is my code which is almost identical to when I use MySQL, but with this snippet I get the error "Keyword not supported: 'flush interval'". Has anyone been able to fetch custom table data with Azure SQL?
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["umbracoDbDSN"];
using(SqlConnection con = new SqlConnection(cs.ToString()))
{
string sql = "SELECT * FROM [dbo].[MyTable]";
con.Open();
using(SqlCommand cmd = new SqlCommand(sql,con))
{
SqlDataReader reader = cmd.ExecuteReader();
}
con.Close();
}
If you are accessing this in an Umbraco-based website and have the tables within the same database that Umbraco is using, you can get the connection string by accessing the ConnectionString property on the DatabaseContext:
using (var con = new SqlConnection(Umbraco.Core.ApplicationContext.Current.DatabaseContext.ConnectionString)) {
// Your code here
}
However, you may find it advantageous to use the built-in PetaPoco support that Umbraco offers. There's a good example of using PetaPoco here: http://creativewebspecialist.co.uk/2013/07/16/umbraco-petapoco-to-store-blog-comments/

Create new SQLite database on WinRT?

I want to create a new database from C# code in my WinRT app. I searched the Web and the way to do that appears to be the SQLiteConnection.CreateFile() method. However, that method does not exist in the SQLite namespace, at least in the WinRT version. I installed SQLite using the NuGet packge name "sqlite-net" and included the sqlite3.dll into my project. I do see properly methods like CreateTable(), Query(), etc. but not CreateFile(). Where is it? Or does the WinRT package use a different method for creating database files from code?
var db = new SQLiteConnection(databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite);
is how I did it.
One of the times where Microsoft provides a straightforward example:
https://learn.microsoft.com/en-us/windows/uwp/data-access/sqlite-databases
await ApplicationData.Current.LocalFolder.CreateFileAsync("sqliteSample.db", CreationCollisionOption.OpenIfExists);
string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
using (SqliteConnection db =
new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
String tableCommand = "CREATE TABLE IF NOT " +
"EXISTS MyTable (Primary_Key INTEGER PRIMARY KEY, " +
"Text_Entry NVARCHAR(2048) NULL)";
SqliteCommand createTable = new SqliteCommand(tableCommand, db);
createTable.ExecuteReader();
Because depending on how you add sqlite to a UWP project, not having createfile() available is still an issue in 2021.

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