以编程方式创建了本地数据库,但是我无法在其中创建表?

时间:2018-07-19 11:08:06

标签: c# database local mdf

我一直在寻找解决方案,但找不到任何东西。

我必须创建一个文件夹,然后我必须以编程方式在其中创建数据库。我已经创建了文件夹和数据库,但是当我想在其中创建表时,首先我什么也没说(我猜它创建了),但是我看不到任何地方的表,如果我要第二次尝试,它会说“那里已经是数据库中的对象名称,例如“ table_name”。

这是我的代码:

public void CreateFolder(string folderName)
{
    int count = 0;
    string path = "C:\\Users\\aabbccdd\\Documents\\";
    string[] folders = Directory.GetDirectories(path);
    foreach (var item in folders)
    {

        string dosyaAdi = item.Substring(path.Length);
        if (dosyaAdi.Length >= folderName.Length)
        {
            if (folderName == item.Substring(path.Length, folderName.Length))
            {
                count = count + 1;
            }
        }
    }


public void CreateSqlDatabase(string filename)
{
    string databaseName = System.IO.Path.GetFileNameWithoutExtension(filename);
    using (var connection = new System.Data.SqlClient.SqlConnection(
        "Data Source=.\\sqlexpress;Initial Catalog=master; Integrated Security=true;User Instance=True;"))
    {
        try
        {
            try
            {
                connection.Open();
                using (var command = connection.CreateCommand())
                {
                    command.CommandText =
                        String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
                    command.ExecuteNonQuery();
                    MessageBox.Show("Database başarılı bir şekilde oluşturuldu.", "Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btn_forward.Visible = true;

                    command.CommandText =
                        String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
                    command.ExecuteNonQuery();



                    command.CommandText = String.Format("IF EXISTS (SELECT * FROM sysobjects WHERE name='cftc_fabrika') alter table cftc_fabrika alter column asuman varchar(100) ELSE create table cftc_fabrika(asuman varchar(100))");

                    command.ExecuteNonQuery();

                }

            }

            catch (SystemException ex) // Change exception type based on your underlying data provider
            {
                if (ex.Message.ToLower().Contains("already exists. choose a different database name"))
                {
                    var match = Regex.Match(ex.Message, "LDATABASE '(.*)' already exists.",
                        RegexOptions.IgnoreCase);

                    if (match.Success)
                    {
                        String dbFileName = match.Groups[1].Value;
                        Process p = new Process();
                        p.StartInfo.UseShellExecute = true;
                        p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        p.StartInfo.FileName = String.Format("{0}/Tools/SSEUtil.exe",
                            Environment.CurrentDirectory);
                        p.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
                        p.StartInfo.Arguments = String.Format("-d \"{0}\"", dbFileName);

                        p.Start();
                    }
                }
            }
            finally
            {
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                }
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Hata" + ex.ToString());
        }

    }
}

1 个答案:

答案 0 :(得分:0)

这样,您可以创建数据库,然后使用此数据库名称创建表

   String str;
        SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");

        str = "CREATE DATABASE MyDatabase ON PRIMARY " +
            "(NAME = MyDatabase_Data, " +
            "FILENAME = 'C:\\MyDatabaseData.mdf', " +
            "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
            "LOG ON (NAME = MyDatabase_Log, " +
            "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
            "SIZE = 1MB, " +
            "MAXSIZE = 5MB, " +
            "FILEGROWTH = 10%)";

        SqlCommand myCommand = new SqlCommand(str, myConn);
        try 
        {
            myConn.Open();
    myCommand.ExecuteNonQuery();
    MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (System.Exception ex)
        {
    MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        finally
        {
    if (myConn.State == ConnectionState.Open)
    {
        myConn.Close();
    }
        }

对于表格,请执行以下操作:-

var commandStr= "If not exists (select name from sysobjects where name = 'Customer') CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime)";

using (SqlCommand command = new SqlCommand(commandStr, con))
command.ExecuteNonQuery();

Blog For you