尝试在foreach中创建时未形成字符串

时间:2012-09-28 22:23:01

标签: c# string oracle arraylist parameter-passing

我有一个班级People_val。我在另一个类中列出了这个类。现在我在这个列表上做一个foreach,对于我称之为ToSQL()函数的每个项目,它给我一个插入查询。列表计数超过50,000条记录。第9774号查询未完全形成。 9771 INSERT INTO CONVERSION_PEOPLE_VALIDATION VALUES(16413,'Jnto','Johnson',因此,命令未执行且事务被回滚。 我应该怎么做以获得foreach中的完整字符串。

public class People_Val
{
    public int MEMBERS_ID;
    public string PFirstName;
    public string PLastName;

    public DateTime? BIRTH_DATE;
    public string RELATIONSHP;

    public string ToSQL()
    {            
        return string.Format("INSERT INTO CONVERSION_PEOPLE_VALIDATION VALUES ({0},'{1}','{2}','{3}', TO_CHAR('{4}', 'DD-MON-YYYY'))",
                             MEMBERS_ID, PFirstName.Replace("'","\""), PLastName.Replace("'","\""), RELATIONSHP, BIRTH_DATE);
    }
}

public void insertPeopleValTrans(List<People_Val> _lstPeoplevals)
{
    int count=0;
    TextWriter tw = new StreamWriter(@"C:\PeopleVal.txt");
    using (OracleConnection conn = new OracleConnection(connectionStr)) {
        conn.Open();
        OracleTransaction trans;
        trans = conn.BeginTransaction();
        try {
            foreach (People_Val peopleVal in _lstPeoplevals) {
                OracleCommand cmd = new OracleCommand(peopleVal.ToSQL(), conn, trans);
                cmd.ExecuteNonQuery();
                count++;
                if (count % 500 == 0) {
                    Console.WriteLine("saving " + count.ToString() + " Records");
                }
                tw.WriteLine(count.ToString()+" "+ peopleVal.ToSQL());
            }
            trans.Commit();
            tw.Close();
        } catch (Exception ex) {
            Console.WriteLine(ex.Message);
            trans.Rollback();
        }
        conn.Close();
    }          
}

2 个答案:

答案 0 :(得分:3)

您可能在某些数据中包含撇号,导致查询失败。

尝试参数化输入...看起来RELATIONSHIP字段是原始数据,可能是问题所在。看看http://www.devart.com/dotconnect/oracle/articles/parameters.html我很确定这会让你感到厌烦。

粘贴在第9771行让我们看看......

答案 1 :(得分:0)

是否真的有必要让所有50000条记录一起成功或失败?否则跳过交易或至少提交一点,可能是......

if (count % 500 == 0)
{
    trans.Commit();
    Console.WriteLine("saving " + count.ToString() + " Records");
    trans = conn.BeginTransaction();
}

我同意previos评论,这将是使用Entity Framework Code First的最小努力。