简体   繁体   English

SQL insert命令仅在循环中运行一次

[英]SQL insert command only working once in a loop

This is s for loop and it will go to the times and will put the time column as true. 这是for循环,它将转到时间并将时间列设置为true。 This works for the first time, but when the time increases by 0.5, it stays false. 这是第一次使用,但是当时间增加0.5时,它仍然是错误的。 The for loop is working as i tried a MessageBox.Show("" + Time1 + ""); for循环正在尝试MessageBox.Show(“”+ Time1 +“”); inside the for loop. 在for循环中。

for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
        {
            string Time1 = Time.ToString("0.00");


            try
            {
                SqlConnection cn = new SqlConnection("Data Source=.\\SqlExpress;Initial Catalog=AllensCroft;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework;");

                cn.Open();
                SqlCommand Command = new SqlCommand("INSERT INTO Slots ([Date],[RoomID],[" + Time1 + "]) Values (@date,@room,1)", cn);
                Command.Parameters.AddWithValue("date", date);
                Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);

                Command.ExecuteNonQuery();


                try
                {
                    cn.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }

Here is what the database looks like, the first true field works, but when it loops to another time, it remains false, I think it may be due to the fact that if I have an existing row with that date (date is primary key), i cannot update that row, so i might need to have an IF the row exists, update, else create a new row. 这是数据库的样子,第一个真正的字段工作,但是当它循环到另一个时间时,它仍然是假的,我认为这可能是因为如果我有一个具有该日期的现有行(日期是主键) ),我无法更新该行,所以我可能需要一个IF存在行,更新,否则创建一个新行。

插槽数据库

You are doing an insert. 你正在插入。 In every loop you insert a new row and set the value true only for the column which name is equal to the current value of the variable Time1 . 在每个循环中,您插入一个新行,并仅为名称等于变量Time1的当前值的列设置值true。

Not having a value for the other columns they probably default to false. 没有其他列的值,他们可能默认为false。 (bit columns I suppose) (我想比特列)

If you want a default to true for every column perhaps it is better to change the database schema adding the default for every time column, otherwise you need a long list of parameters 如果您希望每列的默认值为true,那么最好更改数据库架构,为每个时间列添加默认值,否则您需要一长串参数

EDIT: If your logic dictates that you need only one row per date and set every time column to true if you enter the situation above then you can move this logic in the database using a stored procedure: 编辑:如果您的逻辑规定每个日期只需要一行,并且如果输入上述情况,则每次将列设置为true,则可以使用存储过程在数据库中移动此逻辑:

CREATE PROCEDURE InsertOrUpdateSlotFromCode(@dt smalldatetime, @roomID int)
AS
BEGIN
    DECLARE @cnt INT
    SELECT  @cnt = COUNT(*) from Slots WHERE [Date] = @dt
    if @cnt = 0 
        INSERT INTO Slots ([Date],[RoomID], <here all the time fields> VALUES (@dt, @roomID, 1, ....)
    else
        UPDATE Slots SET [09.00] = 1, ..... WHERE [Date] = @dt
    End 
END

then your code call the sp 然后你的代码调用sp

using(SqlConnection cn = new SqlConnection(.........))
{
    cn.Open();
    SqlCommand Command = new SqlCommand("InsertOrUpdateSlotFromCode", cn);
    Command.CommandType = CommandType.StoredProcedure;
    Command.Parameters.AddWithValue("date", date);
    Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
    Command.ExecuteNonQuery();
}

Of course now you can completely get rid of the loop 当然现在你可以完全摆脱循环

Try this, you don't have to open connection in each loop, create your sql statement first looping through each value and then do insert using one statement 试试这个,你不必在每个循环中打开连接,首先创建你的sql语句循环遍历每个值,然后使用一个语句插入

private string CreateInsertStatement(double time_began_5, double time_finished_5)
{
   string sql = "INSERT INTO Slots ([Date],[RoomID],";
   string valuesql = " Values (@date,@room,";
   for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
   {
    string Time1 = Time.ToString("0.00");
    sql+ = "[" + Time1 + "],";
    valuesql+ = "1,";
   }
   sql = sql.TrimEnd(',') + ") ";
   valuesql = valuesql.TrimEnd(',') + ") ";

   return sql + valuesql;
}

private string CreateUpdateStatement(double time_began_5, double time_finished_5)
{
    string sql = "UPDATE Slots SET ";
    string wheresql = " WHERE [Date] = @date AND [RoomID] = @room";
    for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
    {
        string Time1 = Time.ToString("0.00");
        sql+ = "[" + Time1 + "] = 1,";        
    }
    sql = sql.TrimEnd(','); 
    return sql + wheresql;
}

Then in you actual insert code: 然后在你的实际插入代码:

try
{
    SqlConnection cn = new SqlConnection("Data Source=.\\SqlExpress;Initial Catalog=AllensCroft;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework;");

    cn.Open();
    SqlCommand Command;
    //check if row exists 
    Command = new SqlCommand("select count(*) from Slots WHERE [Date] = @date AND [RoomID] = @room", cn);
    Command.Parameters.AddWithValue("date", date);
    Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);

    var cnt = Command.ExecuteScalar();
    if(cnt!=null)
    {
        string sqlstr = ""
        if(Int32.Parse(cnt.ToString()) > 0)
        {
            sqlstr = CreateUpdateStatement(time_began_5,time_finished_5);
        }
        else if(Int32.Parse(cnt.ToString()) == 0)
        {
            sqlstr = CreateInsertStatement(time_began_5,time_finished_5);
        }
        Command = new SqlCommand(sqlstr, cn);
        Command.Parameters.AddWithValue("date", date);
        Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
        Command.ExecuteNonQuery();
    }
    try
    {
        cn.Close();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM