数据库
首页 > 数据库> > C#-等待创建数据库完成

C#-等待创建数据库完成

作者:互联网

我有这样的代码:

using (var sqlConnection = new SqlConnection(connectionString))
{
  sqlConnection.Open();
  using (var sqlCommand = new SqlCommand(scriptText, sqlConnection))
  {
    sqlCommand.ExecuteNonQuery();
  }
}

我第一次调用它来创建一个数据库,然后形成一个到该数据库的连接字符串,并尝试做一些工作(“打开”工作正常,并说该连接实际上已为第二个连接打开).但是我收到“远程主机强行关闭了现有连接”,并且可以看到sql日志“找不到数据库ID9.数据库可能尚未激活或正在转换中”.因此,实际上ExecuteNonQuery在作业完成之前返回.当然,我可以对它进行垃圾邮件处理,直到情况发生变化为止,但是还有更好的方法等待数据库准备工作吗?

解决方法:

这个完整的示例对我有用.

它创建数据库,创建表,在表中放置一行.

不确定您的问题出在哪里.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace GranadaCoder.PlaygroundConsole.SqlStuff
{
    public class SqlPlayground
    {

        public static void EntryPointStuff()
        {
            string databaseName = "MyFirstDatabaseABC";
            string connectionString = string.Empty;
            string commandText = string.Empty;
            int returnValue = 0;
            string msg = string.Empty;

            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder["Initial Catalog"] = "master";
            builder["integrated Security"] = true;
            builder["Server"] = @"MyMachine\MyInstance";
            connectionString = builder.ConnectionString;


            commandText = string.Format("IF EXISTS (Select * from sys.databases where name = N'{0}') DROP DATABASE [{0}]", databaseName);
            returnValue = RunACommand(connectionString, commandText);
            msg = string.Format("'{0}', {1}", returnValue, commandText);
            Console.WriteLine(msg);

            commandText = string.Format("IF NOT EXISTS (Select * from sys.databases where name = N'{0}') CREATE DATABASE [{0}]", databaseName);
            returnValue = RunACommand(connectionString, commandText);
            msg = string.Format("'{0}', {1}", returnValue, commandText);
            Console.WriteLine(msg);

            /* Change the Catalog */
            builder["Initial Catalog"] = databaseName;
            connectionString = builder.ConnectionString;


            commandText = "if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CodeCategory]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)    BEGIN       DROP TABLE [dbo].[CodeCategory]     END ";
            returnValue = RunACommand(connectionString, commandText);
            msg = string.Format("'{0}', {1}", returnValue, commandText);
            Console.WriteLine(msg);

            commandText = "CREATE TABLE [dbo].[CodeCategory] (    CodeCategoryKey           [smallint] not null     , CodeCategoryName      varchar(64) not null  ) ";
            returnValue = RunACommand(connectionString, commandText);
            msg = string.Format("'{0}', {1}", returnValue, commandText);
            Console.WriteLine(msg);


            commandText = "INSERT INTO [dbo].[CodeCategory] (     CodeCategoryKey       , CodeCategoryName    ) Select 1001 , 'MyFirstCodeCategory' ";
            returnValue = RunACommand(connectionString, commandText);
            msg = string.Format("'{0}', {1}", returnValue, commandText);
            Console.WriteLine(msg);

            commandText = "Select Count(*) from [dbo].[CodeCategory]";
            returnValue = RunACommand(connectionString, commandText);
            msg = string.Format("'{0}', {1}", returnValue, commandText);
            Console.WriteLine(msg);

        }




        private static int RunACommand(string connectionString, string scriptText)
        {

            int returnValue = 0;

            using (var sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();
                using (var sqlCommand = new SqlCommand(scriptText, sqlConnection))
                {
                    returnValue = sqlCommand.ExecuteNonQuery();
                }
                sqlConnection.Close();
            }

            return returnValue;
        }






    }

}

这对我有用(无一例外):

    static void Main(string[] args)
    {

        try
        {

            SqlPlayground.EntryPointStuff();

            Console.WriteLine("Press Enter after deleting the database in SSMS manually with 'Close Existing Connections' checked.");
            Console.ReadLine();

            SqlPlayground.EntryPointStuff();


        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }


        Console.WriteLine("Pressing Enter To End");
        Console.ReadLine();

    }

标签:database-connection,c,sql-server
来源: https://codeday.me/bug/20191122/2061763.html