简体   繁体   English

使用 C# 动态创建数据库

[英]Create Database Dynamically Using C#

I am trying to create a database using this code:我正在尝试使用以下代码创建数据库:

var createDatabaseQuery = "exec ('CREATE DATABASE ' + @db)";

var sqlCommand = new SqlCommand(createDatabaseQuery, sqlConnection);
sqlCommand.Parameters.Add("@db", SqlDbType.Text);
sqlCommand.Parameters["@db"].Value = "DbName";

sqlCommand.ExecuteNonQuery();

The above works perfectly but I try to do concatenation as follows, it throws an exception:以上工作完美,但我尝试按如下方式进行连接,它会引发异常:

var sqlCommand = new SqlCommand(createDatabaseQuery, sqlConnection);
sqlCommand.Parameters.Add("@db", SqlDbType.Text);
sqlCommand.Parameters["@db"].Value = "DbName" + CustomId; //Doing the concatenation here

Exception:例外:

System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '-' System.Data.SqlClient.SqlException (0x80131904):'-' 附近的语法不正确

I know, there could be better ways to do it.我知道,可能有更好的方法来做到这一点。 But is there any way that I can make the above work?但是有什么办法可以使上述工作?

Time to learn the real intricate sides of SQL.是时候了解 SQL 真正复杂的一面了。

The way you wan t to write it - is incorrect in multiple ways.你想写它的方式——在很多方面都是不正确的。 DEBUG THE SQL.调试 SQL。 Do not care about the C# code, look at the SQL...不关心C#代码,看SQL...

In your case - naming conversions.在您的情况下 - 命名转换。

Tables, databases etc. can not contains a "-" - OR they must be marked.表格、数据库等不能包含“-” - 或者它们必须被标记。

CREATE DATABASE my-database -> Error CREATE DATABASE [my-database] -> correct, the [] brackets names and thus... no processing of the "-" is tried. CREATE DATABASE my-database -> 错误 CREATE DATABASE [my-database] -> 正确,[] 括号名称,因此...没有尝试处理“-”。

This is quite clear in the SQL documentation, but a part many people overlook (mostly because in most cases it does not matter).这在 SQL 文档中非常清楚,但是很多人忽略了一部分(主要是因为在大多数情况下它无关紧要)。 They likely wonder why generators bracket every item name (Database, schema, table, COLUMN).他们可能想知道为什么生成器将每个项目名称都括起来(数据库、模式、表、列)。 Well, that is the reason.嗯,这就是原因。 What do you think "-1" means?你认为“-1”是什么意思? Minus one, processing, or part of a name - the server has no way to determine this.减一、处理或名称的一部分 - 服务器无法确定这一点。 Help him.帮助他。

You need to make sure you are quoting the name correctly using QUOTENAME , because it contains characters that need escaping.您需要确保使用QUOTENAME正确引用名称,因为它包含需要 escaping 的字符。

var createDatabaseQuery = "exec ('CREATE DATABASE ' + QUOTENAME(@db))";

Also, the parameter type should be nvarchar(128)此外,参数类型应为nvarchar(128)

sqlCommand.Parameters.Add("@db", SqlDbType.NVarChar, 128).Value = "DbName" + CustomId;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM