[英]Can't create a database programmatically
I am trying to create a database through visual studios, however I can't. 我正在尝试通过视觉工作室创建数据库,但是我不能。 I get the error message: "Cannot open database "database1" requested by the login. the login failed. Login failed for user '123'" However if I manually create "database1" in SQL server studios and then try to connect to it via c# code I can connect to the database fine. 我收到错误消息:“无法打开登录名请求的数据库“ database1”。登录失败。用户'123'的登录失败”但是,如果我在SQL Server Studio中手动创建“ database1”,然后尝试通过它连接C#代码我可以连接到数据库很好。 I have created a user with the id 123 and password abc in server studios with every server role checkbox ticked. 我在服务器工作室中创建了一个ID为123,密码为abc的用户,并选中了每个服务器角色复选框。 I am using SQL Express 2012. 我正在使用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();
}
}
}
基于注释:如果您尝试以编程方式创建数据库,则无法使用与未出生数据库的连接,因此在这种情况下,您必须打开与master
数据库的连接,如下所示:
"Server = localhost; Database = master; User Id = 123; Password = abc;"
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();
}
}
Please try this above code. 请尝试上面的代码。 Its working for me.Don't give database name before you create the database. 它对我有用。创建数据库之前,请不要提供数据库名称。 Use database master for initialize the database connection. 使用数据库主数据库初始化数据库连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.