亚马逊AWS RDS - 如何编程创建在C#中的MS SQL数据库? [英] Amazon AWS RDS - How to Programmatically Create a MS SQL Database in C#?
本文介绍了亚马逊AWS RDS - 如何编程创建在C#中的MS SQL数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建运行MS SQL亚马逊AWS RDS实例。我已经成功地之所以能在C#中使用以编程方式创建数据库:
I've created an Amazon AWS RDS instance running MS SQL. I've successfully been able to programmatically create a database in C# using:
SqlConnection myConn = new SqlConnection("Data Source=<public-ip-name>;Persist Security Info=True;User ID=<userid>;PWD=<pwd>;");
myConn.Open();
string str = "CREATE DATABASE contacts";
SqlCommand cmd = new SqlCommand(str, myConn);
cmd.ExecuteNonQuery();
不过,我一直没能做出更复杂的连接字符串的工作:
However, I haven't been able to make a more complex connection string work:
str = "CREATE DATABASE contacts ON PRIMARY " +
"(NAME = Contacts_Data, " +
@"FILENAME = 'c:\contacts.mdf', " +
"SIZE = 4MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = Contacts_Log, " +
@"FILENAME = 'c:\contacts.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
错误(5)似乎抱怨C:\不能写入。也许它不存在?如果我省略了文件名,错误抱怨我忽略它。什么是文件名,正确的价值?看来,文件名必须指定现有文件的路径。
The error (5) seems to complain that C:\ can't be written to. Perhaps it doesn't exist? If I omit FILENAME, an error complains that I omitted it. What is the correct value for FILENAME? It appears that FILENAME must specify an existing file path.
推荐答案
我有codeD jtseng的答案在C#
I've coded jtseng's answer in C#
static string GetDBPath(SqlConnection myConn, string db = "master")
{
string sqlstr = "USE " + db + "; EXEC sp_helpfile";
SqlCommand command = new SqlCommand(sqlstr, myConn);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow);
reader.Read();
string filename = reader["filename"].ToString();
string directory = System.IO.Path.GetDirectoryName(filename);
return directory;
}
通过名为:
SqlConnection myConn = new SqlConnection("Data Source=<public ip>;Persist Security Info=True;User ID=<userid>;PWD=<pwd>;");
myConn.Open();
string dbPath = GetDBPath(myConn); // default db is master
这篇关于亚马逊AWS RDS - 如何编程创建在C#中的MS SQL数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文