0

我无法弄清楚我在这里做错了什么,在调试器中,当我设置断点时,字符串中都有字符串值,但是当需要将它们插入表中时,什么都没有放入。

该表定义如下

CREATE TABLE [dbo].[tblMissEvents] (
[EventID]          INT            IDENTITY (1, 1) NOT NULL,
[EventTime]        NVARCHAR (MAX) NULL,
[MIS_Event_Action] VARCHAR (50)   NULL,
[Bogey_Type]       VARCHAR (50)   NULL,
PRIMARY KEY CLUSTERED ([EventID] ASC)

);

我的代码:

        string date = DateTime.Now.ToString();
        string MISaction = text1.Text;
        string BogeyType = text2.Text;

        try
        {
            con = new SqlConnection();
            con.ConnectionString =
                @"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\MissileEvents.mdf;integrated security=True;MultipleActiveResultSets=True;Connect Timeout=30";
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText =
                "INSERT into tblMissEvents (EventTime, MIS_Event_Action, Bogey_Type) Values (@date, @MISaction, @BogeyType)";  
            cmd.Parameters.AddWithValue("@date", date);
            cmd.Parameters.AddWithValue("@MISaction", MISaction);
            cmd.Parameters.AddWithValue("@BogeyType", BogeyType);
            cmd.Connection = con;
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        con.Close();

有什么想法吗??我没有例外,只是没有进入我的桌子。

为 Arshad 编辑:

        con = new SqlConnection();
        con.ConnectionString =
            @"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\MissileEvents.mdf;integrated security=True;MultipleActiveResultSets=True;Connect Timeout=30";
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText =
            "INSERT into tblMissEvents (MIS_Event_Action, Bogey_Type) Values (@date, @MISaction, @BogeyType)";  
        cmd.Parameters.AddWithValue("@date", date);
        cmd.Parameters.AddWithValue("@MISaction", MISaction);
        cmd.Parameters.AddWithValue("@BogeyType", BogeyType);
        cmd.Connection = con;
        cmd.ExecuteNonQuery();

更新:: 代码很好,它在我的 bin\Debug 目录中复制了数据库,这就是所有数据的去向。可能与我的连接字符串设置有关。谢谢大家!

4

1 回答 1

0

您也可以将 null 值传递为:

 cmd.CommandText =
            "INSERT into tblMissEvents (EventTime, MIS_Event_Action, Bogey_Type)
                                Values (@eventTime, @MISaction, @BogeyType)";  
        cmd.Parameters.AddWithValue("@eventTime", DBNull.Value);          
        cmd.Parameters.AddWithValue("@MISaction", MISaction);
        cmd.Parameters.AddWithValue("@BogeyType", BogeyType);

更新 1

cmd.CommandText =
        "INSERT into tblMissEvents (EventTime,MIS_Event_Action, Bogey_Type) 
                                Values 
                                   (@date, @MISaction, @BogeyType)"; 

更新 2

int RowUpdated=cmd.ExecuteNonQuery();
MessageBox.Show("Number of row updated"+RowUpdated);
于 2013-04-17T02:11:22.787 回答