empty sqlite file after building - c#

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;

Related

Crashing/error on opening SQLite database in UWP/C#

I'm trying to add code to an old UWP app to access an SQLite database. It works fine when debugging in VisualStudio but when I package it for sideloading it breaks.
I've shrunk it down and tried to simplify the code to see if there's any issues. Below is a small bit of code I'd put in to test out what is going on. The code breaks on opening the database. Again, this works fine when debugging in Visual Studio and breaks when sideloaded.
string entry = "";
string dbpath = #"S:\TestDB.db");
using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}"))
{
db.Open();
string textCommand = "SELECT Source from Materials WHERE Material = #keyValue";
SqliteCommand selectCommand = new SqliteCommand(textCommand, db);
selectCommand.Parameters.AddWithValue("#keyValue", "PMMA");
SqliteDataReader query = selectCommand.ExecuteReader();
while (query.Read()) { entry = query.GetString(0); }
db.Close();
}
return entry;
Does anyone have anything I can try out?
Crashing/error on opening SQLite database in UWP/C#,'Unable to open database file' Is there a way I can get more info out of it.
I'm afraid you can't access db file where in the S disk with path directly. In UWP it only has permission access local folder with path. So we suggest you place your db file into LocalFolder like this document.
string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
using (SqliteConnection db =
new SqliteConnection($"Filename={dbpath}"))
I found someone else who had a similar problem while searching for the answer to my question. I messaged them and they told me to put:
<rescap:Capability Name="developmentModeNetwork" />
in my manifest.
Seemed to do the trick.

Cannot add sqlite db file to Word adding deployment

I developed C# Word add-in which populates some data from database file. It is working fine while I am running through Visual studio running. But if I publish it cannot connect to database.
Here is how I get data from database:
SQLiteConnection con = new SQLiteConnection(ThisAddIn.connectionString);
con.Open();
var command = con.CreateCommand();
command.CommandText =
#"
SELECT *
FROM JK
WHERE article_number = $article_number
";
command.Parameters.AddWithValue("$article_number", textFromDoc);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var title = reader.GetString(2);
var article = reader.GetString(3);
ResultForm resultForm = new ResultForm();
resultForm.setArticle(title, article);
resultForm.ShowDialog();
}
}
public static string connectionString = #"Data Source=E:\projects\c#\TBPWordAddin\WordAddIn1\codexes.db";
Am I doing something wrong or do I need to include file in another way? Any help will be appreciated.
Also I tried publishing using Visual studio installer and it connected to database but the add in didnot lounched on other computers.
The connection string contains an absolute path which can be changed after publishing an application. I'd suggest using a relative path instead - in that case you will be able to find the Db easily. You may check out the following threads for more information on such kind of issues:
Connection string with relative path to the database file
How to give relative path of connection string or data source in windows form application
But if I publish it cannot connect to database.
Make sure the Db path (see the connection string) corresponds to the hardcoded value in the application used.

Writing data from C# to a MDF database

I have a C# piece of code which listens for mouse-up events and then the data is to be written to a database. I have a .MDF database file I locally created in Visual Studio within the application. I am using the below code for this.
The thing is when I open the .MDF database file in SQL Server Management Studio after installing the application, I can't see any rows of data. I can see the columns I created but no data. The "Server" in server explorer in Visual Studio shows up to be my laptop number it seems:
private void MouseUpEvent(object sender, KeyEventArgs e)
{
MousePressed = e.KeyCode.ToString();
int Counting = MousePressed.Split('/').Length - 1;
long TimePressed = _MousePressed_Length;
String DateToday = SQLDate;
String TimeToday = SQLTime;
float TimeNow = SQLTimeExactmilliseconds;
var guid = Guid.NewGuid().ToString();
var guid2 = guid + TimeNow;
string sqlCon = #"Data Source=.\SQLEXPRESS;" +
#"AttachDbFilename=|DataDirectory|\Database1.mdf;
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
using (var db = new SqlConnection(sqlCon))
{
db.Open();
var command = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Date);", db);
command.Parameters.AddWithValue("#Date", DateToday);
var command2 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Time);", db);
command2.Parameters.AddWithValue("#Time", TimeToday);
var command3 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Mousepress);", db);
command3.Parameters.AddWithValue("#Mousepress", TimePressed);
var command5 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#TimeExact);", db);
command5.Parameters.AddWithValue("#TimeExact", TimeNow);
var command6 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Id);", db);
command6.Parameters.AddWithValue("#Id", guid2);
command.ExecuteNonQuery();
command2.ExecuteNonQuery();
command3.ExecuteNonQuery();
command5.ExecuteNonQuery();
command6.ExecuteNonQuery();
db.Close();
}
}
When I try to open the .MDF database file in Server Explorer, I get this message from Visual Studio :
Database 'C:\Program Files (x86)\muhammadADIbrahim#outlook.com\Setup_Attention_Assist\Database1.mdf' already exists. Choose a different database name.
An attempt to attach an auto-named database for file C:\Users\muham\OneDrive\Desktop\Attention_Residue\BAAB UL WORK\NIZAM\CURRENT SOFTWARE\NizamSolutionBackup2.6\Nizam.Monitor\Database1.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
The code compiles and works properly so I am guessing this is something that is just to do with the connection to the database.
What should happen is that the .mdf data gets installed along with the .msi file when the user installs the application locally and the data is written to the database. For any user, I should be able to take the local .mdf file and open it in SQL Server Management Studio and view the results.
Thanks,
Ibrahim
The problem with the mdf database is that you need to install SQLSever.
The problem with mySql is similar. SQLLite didn't seem to work well for me either.
I have ended up creating a .txt file for this which for now seems to be working fine.

Failed to attach Sqlite database with special charactesrs in the path

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!

How to save DataSet after adding data?

Yes, I know that this questions has been asked at least 5-10 times in here, but I can't for the life of me get any of the methods to save the data.
The idea is to create a new row in table Companies in column Name (there is only one column) with value "asdf"`.
I've tried combinations of the following:
DatabaseDataSetTableAdapters.CompaniesTableAdapter adapter = new DatabaseDataSetTableAdapters.CompaniesTableAdapter();
DatabaseDataSet ds = new DatabaseDataSet();
adapter.Insert("asdf");
adapter.Fill(ds.Companies);
adapter.Update(ds.Companies);
ds.AcceptChanges();
ds.Companies.AddCompaniesRow("asdf");
ds.Companies.AcceptChanges();
ds.Companies.AddCompaniesRow("asdf");
ds.Companies.Rows[0]["Name"] = "asdf";
adapter.Update(ds.Companies);
I'm using C# WPF .NET 4.5.1
It does add the data, but it doesn't save it when I exit the program - I know that it adds data, because if I call this method twice it crashes, because the value is no longer unique.
Here is the DatabaseDataSetTableAdapters:
http://pastebin.com/gNsaRFD5
This did not work either:
SqlConnection myConnection = new SqlConnection(global::AliBabaMailer.Properties.Settings.Default.DatabaseConnectionString);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("INSERT INTO Companies (Name) " +
"Values ('string')", myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
Ok so your problem is the Connection String:
Properties.Settings.Default.DatabaseConnectionString
This connection string is of the form:
“Data Source=ServerName;AttachDbFilename=|DataDirectory|\DataBaseName;Integrated Security=True”
The |DataDirectory| is usually here:
C:\Users\UserName\AppData
When you save the data it is being saved to a database file at `|DataDirectory| location but when you try to view the data using Server Explorer you are trying to view from a database file which is in your project's folder, that is why If you try to save and then view the data on run time it will work fine because then you will be querying the same database you are storing your data into.
|DataDirectory|:
|DataDirectory| (enclosed in pipe symbols) is a substitution string that indicates the path to the database. It eliminates the need to hard-code the full path which leads to several problems as the full path to the database could be serialized in different places. |DataDirectory| also makes it easy to share a project and also to deploy an application.
For example, instead of having the following connection string:
"Data Source= c:\program files\MyApp\Mydb.sdf"
Using DataDirectory, you can have the following connection string:
“Data Source = |DataDirectory|\Mydb.sdf”
To set the DataDirectory property, call the AppDomain.SetData method. If you do not set the DataDirectory property, the following default rules will be applied to access the database folder:
For applications that are put in a folder on the user's computer, the database folder uses the application folder.
For applications that are running under ClickOnce, the database folder uses the specific data folder that is created.
Link
Coding Advice:
Try to dispose your Command and Connection Objects like this:
using(SqlConnection myConnection = new SqlConnection(global::AliBabaMailer.Properties.Settings.Default.DatabaseConnectionString))
using(SqlCommand myCommand = new SqlCommand("INSERT INTO Companies (Name) " + "Values ('string')", myConnection))
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}

Categories

Resources