C#-以编程方式创建SQL Server表 [英] C# - Create SQL Server table programmatically
问题描述
我正在尝试以编程方式创建SQL Server表。这是代码。
I am trying to create a SQL Server table programmatically. Here is the code.
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);
}
}
当我第二次运行此应用程序时, m出现异常:
When I'm running this application second time I'm getting an exception:
数据库中已经有一个名为'Customer'的对象
"There is already an object named 'Customer' in the database"
但是当我检查数据库时,我没有看到这样的表。
这是我的连接字符串。
but when I check database I don't see such a table.
Here is my connection string.
<connectionStrings>
<add name ="AutoRepairSqlProvider" connectionString=
"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
Integrated Security=True;User Instance=True"/>
</connectionStrings>
当我运行选择查询时;我从现有表中获取结果,因此我认为连接字符串应该可以。希望您会看到问题:/
When I am running select query; I am getting results from existing tables so I think connection string should be OK. Hope you'll see the problem :/
推荐答案
您没有提到初始目录
连接字符串中的名称。将数据库名称命名为初始目录
名称。
You haven't mentioned the Initial catalog
name in the connection string. Give your database name as Initial Catalog
name.
<add name ="AutoRepairSqlProvider" connectionString=
"Data Source=.\SQLEXPRESS; Initial Catalog=MyDatabase; AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
Integrated Security=True;User Instance=True"/>
这篇关于C#-以编程方式创建SQL Server表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!