create Database use C#

MiPakTeh 1,476 Reputation points
2021-11-30T14:10:32.157+00:00

I want create the database file using c#.I have a code bellow to test but that file not appear.

If cant, somebody show me .May be a little step.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataBase_
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {

            GetDbCreationQuery();
        }

        static string GetDbCreationQuery()
        {
            // your db name
            string dbName = "Test_data";

            // path to your db files:
            // ensure that the directory exists and you have read write permission.
            string[] files = { Path.Combine(Application.StartupPath, dbName + ".mdf"),
                       Path.Combine(Application.StartupPath, dbName + ".ldf") };

            // db creation query:
            // note that the data file and log file have different logical names
            string query = "CREATE DATABASE " + dbName +
                " ON PRIMARY" +
                " (NAME = " + dbName + "_data," +
                " FILENAME = '" + files[0] + "'," +
                " SIZE = 3MB," +
                " MAXSIZE = 10MB," +
                " FILEGROWTH = 10%)" +

                " LOG ON" +
                " (NAME = " + dbName + "_log," +
                " FILENAME = '" + files[1] + "'," +
                " SIZE = 1MB," +
                " MAXSIZE = 5MB," +
                " FILEGROWTH = 10%)" +
                ";";

            return query;
        }
    }
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,982 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,016 Reputation points
    2021-11-30T15:11:43.58+00:00

    The following page does what you need, create a new SQL-Server database.

    Edited version, original version used localhost while my revision uses \\SQLEXPRESS and placed into a class.

    using System;  
    using System.Data.SqlClient;  
    using System.IO;  
    using System.Windows.Forms;  
      
    namespace CreateDatabase  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
            }  
      
            private void CreateButton_Click(object sender, EventArgs e)  
            {  
                var (success, exception) = DataOperations.CreateDatabase();  
                if (success)  
                {  
                    MessageBox.Show("Done");      
                }  
                else  
                {  
                    MessageBox.Show($"{exception.Message}");  
                }  
            }  
        }  
      
        public class DataOperations  
        {  
            public static (bool success, Exception exception) CreateDatabase()  
            {  
                var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Sample.mdf");  
                var ldfFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Sample.ldf");  
      
                string connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";  
      
                var commandText = "CREATE DATABASE MyDatabase ON PRIMARY " +  
                                  "(NAME = MyDatabase_Data, " +  
                                  $"FILENAME = '{fileName}', " +  
                                  "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)" +  
                                  "LOG ON (NAME = MyDatabase_Log, " +  
                                  $"FILENAME = '{ldfFileName}', " +  
                                  "SIZE = 1MB, " +  
                                  "MAXSIZE = 5MB, " +  
                                  "FILEGROWTH = 10%)";  
      
      
      
                using (var cn = new SqlConnection(connectionString))  
                {  
                    using (var cmd = new SqlCommand(commandText, cn))  
                    {  
      
                        try  
                        {  
                            cn.Open();  
                            cmd.ExecuteNonQuery();  
                            return (true, null);  
                        }  
                        catch (Exception e)  
                        {  
                            return (false, e);  
                        }  
                    }  
                      
                }  
            }  
        }  
    }  
      
    

2 additional answers

Sort by: Most helpful
  1. Castorix31 80,916 Reputation points
    2021-11-30T14:23:55.303+00:00

    The code you posted just returns a string...

    See old threads like Create .mdf file in code

    0 comments No comments

  2. Artemiy Moroz 271 Reputation points
    2021-12-01T14:40:14.417+00:00

    Hi there!
    If you have a small desktop program that does not envisage many simultaneous users I would advise you to use SQLite database. It is very easy to catch up. But if you are building a more sophisticated application, you may want to use Microsoft SQL Server. SQLite vs SQL Server Comparison

    0 comments No comments