转换Varchar值时转换失败' ListViewItem:{2}'到数据类型int

时间:2014-04-29 11:41:52

标签: c# sql sql-server c#-4.0

以下查询未在数据库中插入值。

代码:

 try
 {
      for (int i = 0; i < listViewSubject.Items.Count; i+=2)
      {
           string query = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES ('" + listViewSubject.Items[i] + "', '" + this.reg_id + "')";
           dal.InsertUpdateDelete(query);
      }
      conn.Close();
 }
 catch (Exception ex)
 {
       MessageBox.Show(ex.ToString());
 }

3 个答案:

答案 0 :(得分:0)

根据您的问题,我理解转换为int时出现问题是错误的。您必须在插入前将主题ID转换为int。

    Try
        {
        for (int i = 0; i < listViewSubject.Items.Count; i+=2)
        {
            string query = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES (" + Int.Parse(listViewSubject.Items[i].Text) + ", " + this.reg_id + ")";
            dal.InsertUpdateDelete(query);
        }
        conn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

希望this.reg_id也是int。如果没有转换它,因为我转换了主题ID。请注意,我已从

中删除了单引号
  

&#39;&#34; + listViewSubject.Items [i] +&#34;&#39;,&#39;&#34; + this.reg_id +&#34;&#39;

这是使用参数化查询的方法:

  for (int i = 0; i < listViewSubject.Items.Count; i+=2)
        {

         string query = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES (@subjectID,@StdRegId)";
         SqlCommand command = new SqlCommand(query, connection);
         command.Parameters.AddWithValue("@subjectID",Int.Parse(listViewSubject.Items[i].Text));
         command.Parameters.AddWithValue("@StdRegId", this.reg_id);
         command.ExecuteNonQuery();
        }

答案 1 :(得分:0)

似乎listViewSubject.Items[i]返回一个值&#39; ListViewItem:{2}&#39}而不是整数。根据项集合返回的对象类型,您可能需要调试它。可能listViewSubject.Items[i].Value可能有用。

答案 2 :(得分:0)

我不确定你的数据访问层究竟是在幕后做什么,但是使用基本的SqlCommand我倾向于按照以下方式进行插入:

string sql = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES (@SubjectID, @RegID)";
for (int i = 0; i < listViewSubject.Items.Count; i+=2)
{
    using (var conn = new SqlConnection(ConnectionString))
    using (var command = new SqlCommand(sql, connection))
    {
        conn.Open();
        command.Parameters.Add("@RegID", SqlDbType.Int).Value = this.reg_id;
        command.Parameters.Add(SubjectID, SqlDbType.Int).Value = listViewSubject[i].Text;
        command.ExecuteNonQuery();

    }
}