c# - 如果已创建SQL查询,则在文本框上显示消息

时间:2017-10-26 03:21:51

标签: c# sql-server visual-studio

我在c#中创建一个程序,当我按下一个按钮时,它会生成SQL表到我的SQL服务器数据库。如果表已成功创建,则应在程序的大文本框屏幕上显示消息,否则应在文本框屏幕上显示消息错误。

到目前为止,一切都按预期工作,但无论我按下按钮多少次,它都会向屏幕弹出相同的显示消息(已创建表格)。 如果表格在我的数据库中尚不存在,我只希望消息显示(成功)。如果表已存在,则应在屏幕上显示错误消息。我正在考虑使用while语句,但无法解决它是如何解决的。

这是我的代码:

private void btnCreateTables_Click(object sender, EventArgs e)
{
    string query = "IF OBJECT_ID('dbo.AuditCardTypeBenefit_TEST','U') IS NULL ";
    query += "BEGIN ";
    query += "CREATE TABLE[dbo].[AuditCardTypeBenefit_TEST]( "; 
    query += "[AuditID] [decimal](18, 0) IDENTITY(1,1) NOT NULL, ";
    query += "[AuditType] [char](5) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
    query += "[CardTypeBenefitID] [decimal](18, 0) NOT NULL, ";
    query += "[EventCode] [varchar](8) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
    query += "[CardTypeGroupID] [varchar](5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, ";
    query += "[AgeFrom] [int] NULL, ";
    query += "[AgeTo] [int] NULL, ";
    query += "[Gender] [char](1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, ";
    query += "[CreateBy] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
    query += "[CreateDate] [datetime] NOT NULL, ";
    query += "[Status] [char](2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
    query += "[CancelReason] [varchar](250) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
    query += "[LastChangeBy] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, ";
    query += "[LastChangeDate] [datetime] NOT NULL, ";
    query += "[RecordVersion] [timestamp] NOT NULL ";
    query += ") ON [PRIMARY] ";
    query += "END ";

    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

    try
    {
       using (SqlConnection con = new SqlConnection(constr))
       {
           using (SqlCommand cmd = new SqlCommand(query))
           {
               cmd.Connection = con;
               con.Open();
               cmd.ExecuteNonQuery();
               Display("AuditCardTypeBenefit_Test table has been created successfully");
               con.Close();
           }
       }
    }
    catch(Exception ex)
    {
         MessageBox.Show(ex.Message);
         textBox1.AppendText(string.Format("{0}", Environment.NewLine));
         textBox1.AppendText(string.Format("{0} MainPage_Load() exception - {1}{2}", _strThisAppName, ex.Message, Environment.NewLine));
         Debug.WriteLine(string.Format("{0} MainPage_Load() exception - {1}", _strThisAppName, ex.Message));
    }

注意:Display方法负责向屏幕显示消息。

1 个答案:

答案 0 :(得分:0)

SqlCommand.ExecuteNonQuery()方法返回受影响的行数。

  

对于UPDATE,INSERT和DELETE语句,返回值是受命令影响的行数。当插入或更新的表上存在触发器时,返回值包括插入或更新操作影响的行数以及受触发器或触发器影响的行数。 对于所有其他类型的语句,返回值为-1。如果发生回滚,则返回值也为-1

也许在做

if (cmd.ExecuteNoneQuery() == -1)
  Display("AuditCardTypeBenefit_Test table has been created successfully");

con.Close();

会解决你的问题吗?不知道在创建表时它是否只返回0,这只是一个建议。