SqlCommand无法创建表

时间:2016-04-27 11:50:46

标签: c# sql-server

我在使用SqlCommand创建表时遇到问题。代码如下

        string cs = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="+ Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Database\Test.mdf;Integrated Security=True; Database=Test";
        SqlConnection sc = new SqlConnection(cs);
        sc.Open();
        //SqlCommand cmd = new SqlCommand();
        try
        {
            using (SqlCommand command = new SqlCommand(
            "CREATE TABLE Dogs1 (Weight INT, Name TEXT, Breed TEXT)", sc))
            {
                Console.WriteLine(command.ExecuteNonQuery());
            }
        }
        catch
        {
            Console.WriteLine("Table not created.");
        }

我将代码放在Main函数中并运行它。没有错误,可以打开数据库。但是,当我检查数据库时,没有创建表。任何人都可以帮忙看看这里有什么问题吗?谢谢。

谢谢大家。这个问题已经解决了。当我创建Test.mdf时,我实际上是在项目的Database文件夹中创建的。当我双击Test.mdf时,它被链接到Visual Studio中的服务器资源管理器。然后当我将属性更改为Copy Always时,Test.mdf将被复制到bin / Debug / Database /。当我使用Path.GetDirectoryName(Assembly.GetExecutingAssembly()。Location)时,我实际上是在bin / Debug /中操作它,而不是项目文件夹中的那个。结果,看起来没有创建表。所以现在我将bin / Debug / Database中的Test.mdf链接到Server Explorer,我可以看到创建了新表。

1 个答案:

答案 0 :(得分:0)

是的,您已在项目中创建了在SQL Server Management Studio中无法使用的数据库,因为这是本地应用程序数据库。 SSMS中的DB的.mdf文件位置不同。

相关问题