ExecuteNonQuery() 中断循环并且不在 SQL 数据库中插入数据

ExecuteNonQuery() breaks the loop and doesn't insert data in SQL database

这是尝试输入存储在数组中的数据的代码。数组包含数据以及不需要添加到数据库中的空单元格。问题是代码没有抛出任何异常或错误,但它也没有在数据库中插入任何数据!请帮助...提前致谢

public void saveDb(string[,] timeTableId,string[,] start_time,string[,] end_time,string[,] subject_id,string[,] day,string[,] faculty_id)
{
    SqlConnection con;
    SqlCommand cmd;
    con = new SqlConnection("Data Source=.;Initial Catalog=AIS;Integrated Security=True");
    con.Open();
    for (int i = 0; i < 8; i++)
    {
        for (int j = 1; j <= 7; j++)
        {
            if (subject_id[i, j].Length != 0 && subject_id[i, j] != null)
            {
                cmd = new SqlCommand("INSERT INTO TIMETABLE VALUES('" + subject_id[i, j] + "','" + day[i, j] + "','" + start_time[i, j] + "','" + end_time[i, j] + "','" + subject_id[i, j] + "','" + faculty_id[i, j] + "')", con);
                cmd.ExecuteNonQuery();
            }
            else
            { 
            }
        }
    }
    con.Close();
}

尝试使用 SQL Profiler 捕获 SQL 语句,然后 运行 在 SQL Management Studio 上进行查询以发现是否有任何错误。

尝试:

使用parameterized查询并使用Try catch块获取exception if Any

public void saveDb(string[,] timeTableId,string[,] start_time,string[,] end_time,string[,] subject_id,string[,] day,string[,] faculty_id)
{
 SqlConnection con;
  SqlCommand cmd;
    con = new SqlConnection("Data Source=.;Initial Catalog=AIS;Integrated Security=True");
try
{
   if(con.State == ConnectionState.Closed)
          con.Open();

    for (int i = 0; i < 8; i++)
    {
        for (int j = 1; j <= 7; j++)
        {
            if (subject_id[i, j].Length != 0 && subject_id[i, j] != null)
            {
                cmd = new SqlCommand("INSERT INTO [TIMETABLE](col1,col2,col3,col4,col5,col6) VALUES(@col1,@col2,@col3,@col4,@col5,@col6)", con);

cmd.Parameter.AddWithValue("@col1",subject_id[i, j]);
   // convert type here depend upon the col type
    // cmd.Parameter.AddWithValue("@col1",Convert.ToString(subject_id[i, j]));
   //Or  cmd.Parameter.AddWithValue("@col1",Convert.ToDouble(subject_id[i, j]));
cmd.Parameter.AddWithValue("@col2",day[i, j]);
cmd.Parameter.AddWithValue("@col3",start_time[i, j]);
cmd.Parameter.AddWithValue("@col4",end_time[i, j]);
cmd.Parameter.AddWithValue("@col5",subject_id[i, j]);
cmd.Parameter.AddWithValue("@col6",faculty_id[i, j]);

                cmd.ExecuteNonQuery();
            }
        }
    }
}
Catch(Exception e1)
{
  throw new System.ArgumentException(e1.Messege, "Error");
}
Finally
{
   if(con.State == ConnectionState.Open)
        con.Close();
}
}

好的,我正在详细说明....

  1. 使用参数化查询——首先是为了避免SQL注入,这是互联网上的#1漏洞,其次是为了避免这个字符串或日期我需要多少个单引号或双引号? 和类似的东西 - 如果你使用正确类型的参数就没有了,第三个提高性能 - 定义你的参数 一次,多次重复使用它们(并且SQL服务器还将创建一个带有执行计划的SQL语句并重复使用它!)

  2. 对所有一次性 类 使用 **using(....) { .... } 块 - 特别是 SqlConnectionSqlCommandSqlDataReader - 以确保适当并立即处理不需要的对象。

  3. 始终 显式定义要插入的 table 的列列表 - 不要只依赖当前的 table 列的结构和顺序 - 明确说明 你在做什么!

总而言之,您的方法应该看起来像这样:

public void saveDb(string[,] timeTableId,string[,] start_time,string[,] end_time,string[,] subject_id,string[,] day,string[,] faculty_id)
{
    // define connection string - typically should come from a .config file
    string connectionString = "Data Source=.;Initial Catalog=AIS;Integrated Security=True";

    // define the SQL query - with *parameters* - and also: explicitly NAME the columns in your target table!
    // also: did you really want to insert the subject_id twice?
    string insertQry = "INSERT INTO dbo.TIMETABLE (col1, col2, col3, ....) " + 
                       " VALUES(@subject_id, @day, @start_time, @end_time, @subject_id, @faculty_id)";

    // set up your connection and command    
    // you didn't tell us what datatypes those are - maybe you need to adapt those to your situation!
    using (SqlConnection con = new SqlConnection(connectionString))
    using (SqlCommand cmd = new SqlCommand(insertQry, con))
    {
        // define your parameters once, before the loop
        cmd.Parameters.Add("@subject_id", SqlDbType.Int);
        cmd.Parameters.Add("@day", SqlDbType.DateTime);
        cmd.Parameters.Add("@start_time", SqlDbType.Time);
        cmd.Parameters.Add("@end_time", SqlDbType.Time);
        cmd.Parameters.Add("@faculty_id", SqlDbType.Int);

        con.Open();

        // now start the for loops, and set the parameter values        
        for (int i = 0; i < 8; i++)
        {
            for (int j = 1; j <= 7; j++)
            {
                // not sure what these checks should be - left them "as is"
                if (subject_id[i, j].Length != 0 && subject_id[i, j] != null)
                {
                     // set the parameter values
                     cmd.Parameters["@subject_id"].Value = subject_id[i, j];
                     cmd.Parameters["@day"].Value = day[i, j];
                     cmd.Parameters["@start_time"].Value = start_time[i, j];
                     cmd.Parameters["@end_time"].Value = end_time[i, j];
                     cmd.Parameters["@faculty_id"].Value = faculty_id[i, j];

                     // execute query to insert data                     
                     cmd.ExecuteNonQuery();
                }    
            }
        }

        con.Close();
    }
}