Create Database File Example


using System.IO;
using System.Windows.Forms;

namespace MyProjectNamespace
{
	class DatabaseSqlite
	{
		const string SQLITE_DATABASE_FILE_PASSWORD = "add_my_password_here";		//Set as "" for no password

		//*************************************
		//*************************************
		//********** CREATE DATABASE **********
		//*************************************
		//*************************************
		bool CreateDatabase ()
		{
			String FilePath;
			System.Data.SQLite.SQLiteConnection Connection1 = null;

			try
			{
				//----- CHECK DIRECTORY EXISTS -----
				if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + Application.CompanyName + "\\" + Application.ProductName + "\\"))
					Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + Application.CompanyName + "\\" + Application.ProductName + "\\");

				//----- CREATE NEW DATABASE -----
				FilePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + Application.CompanyName + "\\" + Application.ProductName + "\\mydatabasefile.db";
				System.Data.SQLite.SQLiteConnection.CreateFile(FilePath);

				//Password protect the database
				Connection1 = new System.Data.SQLite.SQLiteConnection("data source=" + FilePath);
				Connection1.SetPassword(SQLITE_DATABASE_FILE_PASSWORD);
				Connection1.Open();
				return (true);
			}
			catch (Exception)
			{
				return (false);
			}
			finally
			{
				//----- CLOSE THE DATABASE CONNECTION IF NECESSARY -----
				try
				{
					if (Connection1 != null)
						Connection1.Close();
				}
				catch (Exception)
				{
				}
			}

		}

	}
}

 

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *