gpt4 book ai didi

c# - 将数据库添加到现有 SQL Server 2008

转载 作者:太空狗 更新时间:2023-10-30 02:00:52 25 4
gpt4 key购买 nike

我花了很多时间尝试研究外部资源,但不同的解决方案似乎比我希望的要复杂得多。

我正在努力实现以下目标:

  • 在此本地计算机上的现有 SQL 实例上创建简单数据库。
  • 安全性应该只是一个简单的用户名和密码
  • 不需要其他选项(log、growth、max size等)

这是我第一次尝试将数据库与我的程序集成。使用 SQLite 或 SMO 开始时似乎有些不知所措。我一直在尝试修改此示例代码以使其正常工作:

private void createDatabase()
{
String str;
SqlConnection myConn = new SqlConnection("Server=" + serverName + ";Integrated security=SSPI;database=master");

str = "CREATE DATABASE " + dbName + " ON PRIMARY " +
"(NAME = " + dbName + "_Data, " +
"FILENAME = 'C:\\" + dbName + ".mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = " + dbName + "_Log, " +
"FILENAME = 'C:\\" + dbName + ".ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";

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

关于如何创建简单的查询字符串或其他创建数据库的想法?如果有更好的方法,那很好,但请记住,我只是在开始时尽量保持简单。

最佳答案

使用 SMO:

    Server server = new Server("servername");
Database db = new Database(server, "MyDatabaseName");
db.Create();

要构建 SMO 应用程序,您需要引用 SMO 程序集。单击“添加引用”并导航到文件夹

C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies

添加对这些程序集的引用:

  • Microsoft.SqlServer.ConnectionInfo.dll
  • Microsoft.SqlServer.Smo.dll
  • Microsoft.SqlServer.Management.Sdk.Sfc.dll
  • Microsoft.SqlServer.SqlEnum.dll

将此 using 语句添加到包含上述代码的文件中:

using Microsoft.SqlServer.Management.Smo;

旁注:

关于c# - 将数据库添加到现有 SQL Server 2008,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9146594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com