SQL Server与C#的连接 - >数据库存在吗?

时间:2012-04-12 13:09:44

标签: c# sql-server ssms

在我正在上学的一个小应用程序中,我试图确定是否存在必要的数据库。

如果没有,我想创建它(以及数据库中的表),然后照常使用它。

我正在使用Visual C#Express Edition和SQL Server Express。我在下面写了一个小测试程序......

namespace DatabaseConnectionTest
{
    class Program
    {
        public static SqlConnection con;

        public static void EstablishConnection()
        {
            string userName = "username";
            string password = "password";
            string server = @".\SQLEXPRESS";
            string database = "Blibbity";
            string trustedConnection = "yes";
            string timeout = "30";

            try
            {
                con = new SqlConnection(
                        "user id=" + userName +
                        ";password=" + password +
                        ";server=" + server +
                        ";Trusted_Connection=" + trustedConnection +
                        ";database=" + database +
                        ";connection timeout=" + timeout);
                con.Open();
                Console.WriteLine("Connection successful!");

                var command = new SqlCommand("insert into sometable values ('somedata')", con);
                command.ExecuteNonQuery();
                Console.WriteLine("Insert successful!");

                command = new SqlCommand("select somecolumn from sometable", con);
                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    Console.WriteLine("Fectched data ====> " + reader["somecolumn"].ToString());
                }

                reader.Close();
                Console.WriteLine("Query successful!");

                command = new SqlCommand("delete from sometable where somecolumn = 'somedata'", con);
                command.ExecuteNonQuery();
                Console.WriteLine("Delete successful!");
            }
            catch
            {
                database = "master";

                con = new SqlConnection(
                    "user id=" + userName +
                    ";password=" + password +
                    ";server=" + server +
                    ";Trusted_Connection=" + trustedConnection +
                    ";database=" + database +
                    ";connection timeout=" + timeout);

                con.Open();

                var command = new SqlCommand(@"
                    USE [master]
                    GO

                    /****** Object:  Database [Blibbity]    Script Date: 04/12/2012 07:08:45 ******/
                    CREATE DATABASE [Blibbity] ON  PRIMARY 
                    ( NAME = N'Blibbity', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\Blibbity.mdf' , SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
                     LOG ON 
                    ( NAME = N'Blibbity_log', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\Blibbity_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
                    GO

                    ALTER DATABASE [Blibbity] SET COMPATIBILITY_LEVEL = 100
                    GO

                    IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
                    begin
                    EXEC [Blibbity].[dbo].[sp_fulltext_database] @action = 'enable'
                    end
                    GO

                    ALTER DATABASE [Blibbity] SET ANSI_NULL_DEFAULT OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET ANSI_NULLS OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET ANSI_PADDING OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET ANSI_WARNINGS OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET ARITHABORT OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET AUTO_CLOSE OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET AUTO_CREATE_STATISTICS ON 
                    GO

                    ALTER DATABASE [Blibbity] SET AUTO_SHRINK OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET AUTO_UPDATE_STATISTICS ON 
                    GO

                    ALTER DATABASE [Blibbity] SET CURSOR_CLOSE_ON_COMMIT OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET CURSOR_DEFAULT  GLOBAL 
                    GO

                    ALTER DATABASE [Blibbity] SET CONCAT_NULL_YIELDS_NULL OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET NUMERIC_ROUNDABORT OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET QUOTED_IDENTIFIER OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET RECURSIVE_TRIGGERS OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET  DISABLE_BROKER 
                    GO

                    ALTER DATABASE [Blibbity] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET DATE_CORRELATION_OPTIMIZATION OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET TRUSTWORTHY OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET ALLOW_SNAPSHOT_ISOLATION OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET PARAMETERIZATION SIMPLE 
                    GO

                    ALTER DATABASE [Blibbity] SET READ_COMMITTED_SNAPSHOT OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET HONOR_BROKER_PRIORITY OFF 
                    GO

                    ALTER DATABASE [Blibbity] SET  READ_WRITE 
                    GO

                    ALTER DATABASE [Blibbity] SET RECOVERY SIMPLE 
                    GO

                    ALTER DATABASE [Blibbity] SET  MULTI_USER 
                    GO

                    ALTER DATABASE [Blibbity] SET PAGE_VERIFY CHECKSUM  
                    GO

                    ALTER DATABASE [Blibbity] SET DB_CHAINING OFF 
                    GO", con);

                command.ExecuteNonQuery();
                con.Close();

                database = "Blibbity";

                con = new SqlConnection(
                    "user id=" + userName +
                    ";password=" + password +
                    ";server=" + server +
                    ";Trusted_Connection=" + trustedConnection +
                    ";database=" + database +
                    ";connection timeout=" + timeout);

                con.Open();

                command = new SqlCommand(@"
                    USE [Blibbity]
                    GO

                    /****** Object:  Table [dbo].[sometable]    Script Date: 04/12/2012 07:09:07 ******/
                    SET ANSI_NULLS ON
                    GO

                    SET QUOTED_IDENTIFIER ON
                    GO

                    SET ANSI_PADDING ON
                    GO

                    CREATE TABLE [dbo].[sometable](
                        [somecolumn] [varchar](50) NULL
                    ) ON [PRIMARY]

                    GO

                    SET ANSI_PADDING OFF
                    GO", con);

                command.ExecuteNonQuery();
                con.Close();

                EstablishConnection();
            }
            finally
            {
                con.Close();
                Console.WriteLine("Connection now closed...");
                Console.ReadLine();
            }
        }

        static void Main(string[] args)
        {
            EstablishConnection();
        }
    }
}

显然Blibbity只是一个垃圾数据库。当我点击异常捕获中的第一个ExecuteNonQuery()行时,它告诉我"GO"附近的语法不正确,但我只是使用SQL Server Management Studio复制了数据库/表创建的文本“脚本为“创建为”功能。

有人知道我为什么会遇到这个问题吗?

非常感谢。

2 个答案:

答案 0 :(得分:4)

GO不是sql server命令,它由Management studio解释。如果要实现相同的行为,则必须通过go指令拆分sql命令并按顺序执行每个部分。

答案 1 :(得分:1)

我建议您不要手动创建数据库,而是建议您使用实体框架,它在代码优先方法中内置支持创建新数据库(如果不存在),添加表格甚至用初始数据填充它们。“ p>

因此,您可以自行解决问题,而不是寻找问题的解决方案。