为什么insert语句生成2行?

时间:2012-01-22 15:52:00

标签: asp.net sql-server

我不知道为什么,但是当我在项目中执行insert语句时,它会生成2个相同的行,而不只是生成一个。

为什么会这样?

这是我的代码:

if (ListBox.Items.Count != 0)
        {
            string username = Session["Session"].ToString();

            con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
            con.Open();

            string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";

            SqlCommand comm = new SqlCommand(knowWhichOne, con);
            int userID = (Int32)comm.ExecuteScalar();

            knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";

            comm = new SqlCommand(knowWhichOne, con);
            int classID = (Int32)comm.ExecuteScalar();

            knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";

            comm = new SqlCommand(knowWhichOne, con);
            int schoolID = (Int32)comm.ExecuteScalar();

            if (RadioWords.Checked == true)
            {
                 game = 1;
            }
            else
            {
                 game = 2;
            }
            string arr = "";
            for (int i = 0; i < ListBox.Items.Count; i++)
            {
                arr += ListBox.Items[i] +",";
            }

            string sqlqueryString = "INSERT INTO HistoryOfGames (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID,Arrayarray) VALUES (@GameID, @UserID, @LengthOfArray, @NumberOfErrors, @ClassID, @SchoolID, @Arrayarray);" + "SELECT SCOPE_IDENTITY()";

            SqlCommand commandquery = new SqlCommand(sqlqueryString, con);

            commandquery.Parameters.AddWithValue("GameID", game);
            commandquery.Parameters.AddWithValue("UserID", userID);
            commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
            commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
            commandquery.Parameters.AddWithValue("ClassID", classID);
            commandquery.Parameters.AddWithValue("SchoolID", schoolID);
            commandquery.Parameters.AddWithValue("Arrayarray", arr);

            commandquery.ExecuteNonQuery();





            int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
            con.Close();

            Response.Redirect("NowPlay.aspx?ID="+ IdOfRecentHistoryGame);

        }

4 个答案:

答案 0 :(得分:5)

你正在运行它两次,ExecuteNonQuery()和ExecuteScalar()。摆脱ExecuteNonQuery()。

答案 1 :(得分:2)

你做了

   commandquery.ExecuteNonQuery();

然后就在

之后
   int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();

你执行两次

不要忘记检查代码中的sql注入...

答案 2 :(得分:1)

我会检查两件事:

  • 查看此语句执行的次数(尝试设置断点以验证代码只运行一次)
  • 查看数据库中是否有可能导致插入额外记录的触发器

答案 3 :(得分:-1)

我遇到了同样的问题,我这样处理。不专业但是有效:

Dim x As Boolean = True

If x = True Then

here goes your code to insert to database.

End If

x = False