Home > Software engineering >  Connecting a SQLite database to c#
Connecting a SQLite database to c#

Time:12-11

I am trying to make a very simple windows application that keeps track of time spent on windows and i am still pretty new to C# for now I want
to make something like this:

discord:60min  
valorant:90min  
etc  

This is what is have now, you can check the file structure here:

enter image description here

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SqliteDatabase1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //createTable();
            addrow();
        }

        static void createTable()
        {
            string db = "Data Source=demo.db";
            SQLiteConnection cnn = new SQLiteConnection(db);
            cnn.Open();
            string tbl = "CREATE TABLE Program (id integer primary key, Name varchar(20));";
            SQLiteCommand command = new SQLiteCommand(tbl, cnn);
            command.ExecuteNonQuery();
            cnn.Close();
        }

        public void addrow()
        {
            string db = "Data Source=.\\demo.db";

            using (var connection = new SQLiteConnection(db))
            {
                connection.Open();

                string cmd = "insert into names (name, id) values ('idf if itw worked', 7);";
                SQLiteCommand command = new SQLiteCommand(cmd, connection);
                command.ExecuteNonQuery();
            }
        }
    }
}

This is the code that I am using to add a row to the table in the database, the problem is that if the change the source of the database to the full path for ex: D: ..\\\\..\\\\..\\\\Demo.db, the database is also updated along with the database that will be created in the bin folder. But if I use a relative path, it is not working as expected that is it is not updating the original database but only the one created in the bin folder. If I am missing out something that is required to find the solution please let me know. I will update the question

CodePudding user response:

it's working like this because your current directory is BIN when you run the program. and you have .//demo.db which is again searching in the same BIN directory. So you have to make sure the relative path is also pointing to the actual database. you can get the current directory name by using Directory.GetCurrentDirectory method.

  • Related