0

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!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0
  • you can get datasource from config file, e.g. appsetting.json
KennetsuR
  • 704
  • 8
  • 17
0

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?

Jay K.
  • 546
  • 2
  • 10
  • 17
  • that makes sense too, although if i wanted to keep using the same populated db im currently using right now, is it possible to package it and use it on a different computer without it conflicting? – cryptnec Feb 08 '21 at 03:26