none
How to create Access DB from C# WinForm RRS feed

Answers

  • An alternate using Microsoft.Office.Interop.Access library.

    Notes

    Add a reference to the project

    Create a class as per below (read comments)

    using System;
    using System.Data.OleDb;
    using System.IO;
    using System.Runtime.InteropServices;
    using Microsoft.Office.Interop.Access;
    
    namespace CreateDatabaseLibrary
    {
        public class CreateDatabase
        {
            private readonly string _fileName;
    
            private readonly OleDbConnectionStringBuilder _builder = 
                new OleDbConnectionStringBuilder { Provider = "Microsoft.ACE.OLEDB.12.0" };
    
            /// <summary>
            /// Create database, one table and insert one record
            /// </summary>
            /// <returns></returns>
            public bool Execute()
            {
    
                if (File.Exists(_fileName))
                {
                    File.Delete(_fileName);
                }
    
                if (Create())
                {
                    return CreateTable();
                }
                else
                {
                    return false;
                }
    
            }
            /// <summary>
            /// Create database
            /// </summary>
            /// <returns></returns>
            public bool Create()
            {
    
                try
                {
                    Application app = null;               
                    app = new Application();
                    
                    app.NewCurrentDatabase(
                        _fileName, 
                        AcNewDatabaseFormat.acNewDatabaseFormatAccess2007, 
                        Type.Missing);
    
                    app.CloseCurrentDatabase();
                    Marshal.FinalReleaseComObject(app);
                    app = null;
    
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
    
            }
            /// <summary>
            /// Create table, insert one record
            /// </summary>
            /// <returns></returns>
            public bool CreateTable()
            {
    
                var tableName = "PersonTable";
    
                using (var cn = new OleDbConnection(_builder.ConnectionString))
                {
                    using (var cmd = new OleDbCommand("", cn))
                    {
                        cmd.CommandText = $"CREATE TABLE {tableName} ([Id] COUNTER, [FirstName] TEXT(25),[LastName] TEXT(255), [ActiveAccount] YESNO, [JoinYear] INT)";
    
                        try
                        {
                            cn.Open();
                            // create table
                            cmd.ExecuteNonQuery();
                            // insert one record
                            cmd.CommandText = $"INSERT INTO {tableName} (FirstName,LastName,ActiveAccount,JoinYear) VALUES ('Karen','Payne',True,2019)";
                            cmd.ExecuteNonQuery();
    
                            return true;
                        }
                        catch (Exception)
                        {
                            return false;
                        }
    
                    }
                }
            }
    
            public CreateDatabase(string fileName)
            {
                _fileName = fileName;
                _builder.DataSource = fileName;
            }
        }
    }
    
     

    For demonstration, use a button click event to call the code above.

    private void createDatabaseButton_Click(object sender, EventArgs e)
    {
        var ops = new CreateDatabase(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "database1.accdb"));
        if (ops.Execute())
        {
            MessageBox.Show("Done");
        }
        else
        {
            MessageBox.Show("Failed");
        }
        
    }


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, March 24, 2019 1:09 PM
    Moderator

All replies

  • You can see : How to create an Access database by using ADOX and Visual C# .NET

    (tested on Windows 10 with Microsoft ADO Ext. 6.0 for DDL and Security

    Sunday, March 24, 2019 8:45 AM
  • An alternate using Microsoft.Office.Interop.Access library.

    Notes

    Add a reference to the project

    Create a class as per below (read comments)

    using System;
    using System.Data.OleDb;
    using System.IO;
    using System.Runtime.InteropServices;
    using Microsoft.Office.Interop.Access;
    
    namespace CreateDatabaseLibrary
    {
        public class CreateDatabase
        {
            private readonly string _fileName;
    
            private readonly OleDbConnectionStringBuilder _builder = 
                new OleDbConnectionStringBuilder { Provider = "Microsoft.ACE.OLEDB.12.0" };
    
            /// <summary>
            /// Create database, one table and insert one record
            /// </summary>
            /// <returns></returns>
            public bool Execute()
            {
    
                if (File.Exists(_fileName))
                {
                    File.Delete(_fileName);
                }
    
                if (Create())
                {
                    return CreateTable();
                }
                else
                {
                    return false;
                }
    
            }
            /// <summary>
            /// Create database
            /// </summary>
            /// <returns></returns>
            public bool Create()
            {
    
                try
                {
                    Application app = null;               
                    app = new Application();
                    
                    app.NewCurrentDatabase(
                        _fileName, 
                        AcNewDatabaseFormat.acNewDatabaseFormatAccess2007, 
                        Type.Missing);
    
                    app.CloseCurrentDatabase();
                    Marshal.FinalReleaseComObject(app);
                    app = null;
    
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
    
            }
            /// <summary>
            /// Create table, insert one record
            /// </summary>
            /// <returns></returns>
            public bool CreateTable()
            {
    
                var tableName = "PersonTable";
    
                using (var cn = new OleDbConnection(_builder.ConnectionString))
                {
                    using (var cmd = new OleDbCommand("", cn))
                    {
                        cmd.CommandText = $"CREATE TABLE {tableName} ([Id] COUNTER, [FirstName] TEXT(25),[LastName] TEXT(255), [ActiveAccount] YESNO, [JoinYear] INT)";
    
                        try
                        {
                            cn.Open();
                            // create table
                            cmd.ExecuteNonQuery();
                            // insert one record
                            cmd.CommandText = $"INSERT INTO {tableName} (FirstName,LastName,ActiveAccount,JoinYear) VALUES ('Karen','Payne',True,2019)";
                            cmd.ExecuteNonQuery();
    
                            return true;
                        }
                        catch (Exception)
                        {
                            return false;
                        }
    
                    }
                }
            }
    
            public CreateDatabase(string fileName)
            {
                _fileName = fileName;
                _builder.DataSource = fileName;
            }
        }
    }
    
     

    For demonstration, use a button click event to call the code above.

    private void createDatabaseButton_Click(object sender, EventArgs e)
    {
        var ops = new CreateDatabase(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "database1.accdb"));
        if (ops.Execute())
        {
            MessageBox.Show("Done");
        }
        else
        {
            MessageBox.Show("Failed");
        }
        
    }


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, March 24, 2019 1:09 PM
    Moderator
  • Entity Framework is the newest technology for database programming. As far as I know EF works with Forms applications. Migrations is the newest way to do database maintenance such as creating the database when the application is first run. EntityFrameworkCore.Jet 2.0.0 supports Access databases.


    Sam Hobbs
    SimpleSamples.Info

    Sunday, March 24, 2019 9:09 PM