gpt4 book ai didi

C# - 以编程方式创建 SQL Server 表

转载 作者:可可西里 更新时间:2023-11-01 07:44:05 26 4
gpt4 key购买 nike

我正在尝试以编程方式创建 SQL Server 表。这是代码。

using (SqlConnection con = new SqlConnection(conStr))
{

try
{
//
// Open the SqlConnection.
//
con.Open();
//
// The following code uses an SqlCommand based on the SqlConnection.
//
using (SqlCommand command = new SqlCommand("CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))
command.ExecuteNonQuery();

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

当我第二次运行此应用程序时出现异常:

"There is already an object named 'Customer' in the database"

但是当我检查数据库时,我没有看到这样的表格。
这是我的连接字符串。

<connectionStrings>
<add name ="AutoRepairSqlProvider" connectionString=
"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
Integrated Security=True;User Instance=True"/>
</connectionStrings>

当我运行选择查询时;我正在从现有表中获取结果,因此我认为连接字符串应该没问题。希望你能看到问题:/

最佳答案

您没有在连接字符串中提到 Initial catalog 名称。将您的数据库名称作为 Initial Catalog 名称。

<add name ="AutoRepairSqlProvider" connectionString=
"Data Source=.\SQLEXPRESS; Initial Catalog=MyDatabase; AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
Integrated Security=True;User Instance=True"/>

关于C# - 以编程方式创建 SQL Server 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19589020/

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