我在哪里可以找到数据库? Visual Studio和SQL

时间:2014-05-15 17:03:32

标签: c# sql visual-studio sql-server-express

我已经安装了Visual Studio Ultimate,并安装了Microsoft SQL Server,并尝试使用我在线找到的一些教程找到它的方法。
我已成功编译并运行以下C#代码:

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection sql = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=True;User Instance=True");
            sql.Open();
            SqlCommand command = new SqlCommand("CREATE DATABASE newDatabase;", sql);
            command.ExecuteNonQuery();

            command.CommandText = "CREATE TABLE newTable (name VARCHAR(20), age INT)";
            command.ExecuteNonQuery();

            command.CommandText = "INSERT INTO newTable VALUES ('John', 29)";
            command.ExecuteNonQuery();

            command.CommandText = "INSERT INTO newTable VALUES ('Jack', 21)";
            command.ExecuteNonQuery();

            command.CommandText = "INSERT INTO newTable VALUES ('Robin', 22)";
            command.ExecuteNonQuery();

            command.CommandText = "SELECT * FROM newTable;";
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                Console.WriteLine("{0} is {1} years old.",reader.GetString(0), reader.GetValue(1));
            }

            reader.Close();
            sql.Close();

            Console.ReadLine();

        }
    }
}

这将产生正确的输出,但现在我想实际查看 newDatabase数据库。因此,我搜索了关键字' sql',找到了' Microsoft SQL Server管理工作室'并打开它。
不幸的是,我无法在数据库下找到我的数据库:
enter image description here 它藏在哪里,我怎么能找到它?

1 个答案:

答案 0 :(得分:1)

您需要附加此新数据库。在Databases上,“右键单击”,然后附加数据库。浏览到使用visual studio创建项目时定义的C#项目文件夹,您将在文件夹中找到它。

更新

如果您想直接定义路径以避免搜索,您可以查看此示例,这可能会对您有所帮助:

  String str;
  SqlConnection myConn = new SqlConnection ("Data Source=.\\SQLEXPRESS;Integrated Security=True;User Instance=True");

  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();

   }
  catch (System.Exception ex)
  {
    Console.Write(ex.ToString());
  }
  finally
  {
    if (myConn.State == ConnectionState.Open)
    {
    myConn.Close();
    }
  }