我有一个C#Windows窗体应用程序。我推一个按钮,它应该创建一个表并插入一个值(int)。 我将初始数据库创建为服务数据库(添加新项目>数据>服务数据库)。无法在SQL Server中创建两次相同的表
该按钮的代码是(输出遵循其下方):
private void button1_Click(object sender, EventArgs e)
{
SqlConnection thisConnection = new SqlConnection(Properties.Settings.Default.Database1ConnectionString);
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
try
{
thisConnection.Open();
nonqueryCommand.CommandText = "CREATE TABLE MyTable1 (intColumn int)";
Console.WriteLine(nonqueryCommand.CommandText);
Console.WriteLine("Number of Rows Affected is: {0}", nonqueryCommand.ExecuteNonQuery());
nonqueryCommand.CommandText = "INSERT INTO MyTable1 VALUES (99)";
Console.WriteLine(nonqueryCommand.CommandText);
Console.WriteLine("Number of Rows Affected is: {0}",
nonqueryCommand.ExecuteNonQuery());
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
thisConnection.Close(); // close connection
Console.WriteLine("Connection Closed.");
}
}
OUTPUT: CREATE TABLE MYTABLE1(intColumn INT) 受影响的行号是:-1 INSERT INTO MYTABLE1 VALUES (99) 受影响的行数是:1 连接已关闭。
服务器资源管理器上没有任何显示即使我关闭并重新连接,也没有附加表。
如果我按下按钮,使其发出相同的,我再次得到:在服务器资源管理器
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'MyTable1' in the database.
,但仍然一无所获。
有什么原因令您感到愉快? – 2011-02-23 01:30:22