gpt4 book ai didi

C#使用脚本创建数据库

转载 作者:行者123 更新时间:2023-11-30 22:28:56 26 4
gpt4 key购买 nike

我喜欢在下面的代码中为 FILENAME 使用参数,而不是 N'D:\DBName.mdf' 和 N'D:\DBName.ldf'。

如何在 .sql 文件中更改它以及如何使用参数从 C# 调用它?谢谢。

SQL 脚本:

CREATE DATABASE [DBName] ON  PRIMARY 
( NAME = N'DBName', FILENAME = N'D:\DBName.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'DBName_log', FILENAME = N'D:\DBName.ldf' , SIZE = 3456KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
END

C#代码

string appPathDB = Path.GetDirectoryName(Application.ExecutablePath) + "\\DBName.mdf";
string appPathLog = Path.GetDirectoryName(Application.ExecutablePath) + "\\DBName_log.ldf";

private void CreateDatabase()
{
string connection = "Data Source=localhost;Initial Catalog=master;User ID=sa;Password=abcd1234";
FileInfo file = new FileInfo(Path.GetDirectoryName(Application.ExecutablePath) + "\\DBName.sql");
string script = file.OpenText().ReadToEnd();
ExecSql(script, connection, "DBName");
file.OpenText().Close();
}

public void ExecSql(string sql, string connectionString, string dataBaseNameToPrepend)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(sql);
server.ConnectionContext.Disconnect();
server.ConnectionContext.ExecuteNonQuery(sql);
MessageBox.Show("DB Uploaded.");
}
}

最佳答案

对您的脚本文件进行以下更改并保存。

CREATE DATABASE [DBName] ON  PRIMARY 
( NAME = N'DBName', FILENAME = N'DB_NAME_MDF' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'DBName_log', FILENAME = N'DB_NAME_LDF' , SIZE = 3456KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
END

将以下行添加到您的代码中。

private void CreateDatabase()
{
string connection = "Data Source=localhost;Initial Catalog=master;User ID=sa;Password=abcd1234";
FileInfo file = new FileInfo(Path.GetDirectoryName(Application.ExecutablePath) + "\\DBName.sql");
string script = file.OpenText().ReadToEnd();
script = script.Replace("DB_NAME_MDF", appPathDB).Replace("DB_NAME_LDF", appPathLog);
ExecSql(script, connection, "DBName");
file.OpenText().Close();
}

关于C#使用脚本创建数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10493565/

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