无法以编程方式创建数据库

时间:2016-03-27 04:24:34

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

我正在尝试通过视觉工作室创建数据库,但我无法做到。我收到错误消息:"无法打开数据库" database1"登录请求。登录失败。用户' 123'"登录失败但是,如果我手动创建" database1"在SQL Server工作室然后尝试通过c#代码连接到它我可以很好地连接到数据库。我在服务器工作室中创建了一个id为123和密码为abc的用户,并勾选了每个服务器角色复选框。我正在使用SQL Express 2012。

private void sQLToolStripMenuItem_Click(object sender, EventArgs e)
    {
        bool create_db = false;
        bool create_table = false;


        SqlConnection myConnection = new SqlConnection("Server = localhost; Database = database1; User Id = 123; Password = abc;");
        try
        {

            myConnection.Open();
            MessageBox.Show("We were able to connect to the database!", "Success!");
            create_table = true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            create_db = true;
            MessageBox.Show("There is no database. We will create one.", "No Database Found.");
        }

        // For creating the database if not found
        if (create_db == true)
        {
            String str;
            SqlConnection myConn = new SqlConnection("Server = localhost; Database = database1; User Id = 123; Password = abc;");

            str = "CREATE DATABASE database1";

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

2 个答案:

答案 0 :(得分:1)

基于评论: 如果您尝试以编程方式创建数据库,则无法使用与未出生数据库的连接,因此在这种情况下,您必须打开与master数据库的连接,如下所示:

"Server = localhost; Database = master; User Id = 123; Password = abc;"

答案 1 :(得分:0)

        String str;
        SqlConnection myConn = new SqlConnection("Server=localhost;User Id = 123; Password = abc;database=master");

        str = "CREATE DATABASE database1";

        SqlCommand myCommand = new SqlCommand(str, myConn);
        try
        {
            myConn.Open();
            myCommand.ExecuteNonQuery();
            MessageBox.Show("DataBase is Created Successfully", "Creation", 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();
            }
        }

请尝试以上代码。它为我工作。在创建数据库之前不要给出数据库名称。使用数据库主服务器初始化数据库连接。