往Oracle数据库中插入NCLOB/CLOB类型数据

    最近因为业务需求开发了一个接口用于接收数据,但是总有一些数据报出ORA-01704:字符串文字太长错误。仔细排查后发现,竟然是NCLOB类型字段提示这个错误。NCLOB存储空间有4G,怎么也想不明白为什么会报这个错误。原来因为接口插入数据采用字符串拼接的方式。

 

1 string strSql = "insert into tablename (id) values ('" + id.ToString() + "')";

 

而oracle中会把字符串转为varchar2类型,当字符串非常长,超过4000字符时,就会报ORA-01704错误。

所以为了正确插入NCLOB或者CLOB类型的数据,需要如下面写法

string strSql = "insert into tablename (id) values (:id)";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(strSql);

OracleParameter oracPara = new OracleParameter("id", OracleType.NClob);
oracPara.Value = idvalue;

cmd.Parameters.Add(oracPara);

db.ExecuteNonQuery(cmd);

 

 

 

posted @ 2018-01-02 22:23  星峰踏雪  阅读(10540)  评论(6编辑  收藏  举报