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

时间:2015-08-28 16:42:13

标签: asp.net sql-server executenonquery

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

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();
}

3 个答案:

答案 0 :(得分:0)

尝试使用SQL事件探查器捕获SQL语句,然后在SQL Management Studio上运行查询以发现是否存在任何错误。

答案 1 :(得分:0)

尝试:

使用Try catch查询并使用exception块获取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(); } } if any

{{1}}

答案 2 :(得分:0)

好的,我正在详细阐述......

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

  2. 对所有一次性类使用** using(....) { .... }块 - 尤其是SqlConnectionSqlCommandSqlDataReader - 以确保正确和立即处理不需要的对象。< / p>

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

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

    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();
        }
    }