日期:2014-05-18  浏览次数:20930 次

oledb.net 连接oracle时SQL语句里有单引号问题
在学习oledb.net 连接oracle,SQL语句里有单引号不知怎么解决,请教各位。
如下面一段代码:
C# code

string sDB_Name, sDB_User, sDB_Passwd;
string s_contentA;  //要插入数据库的字符串
sDB_Name = "192.168.1.8";
sDB_User = "dbuser";
sDB_Passwd = "dbpwd";
//连接数据库
OleDbConnection sOraConn = new OleDbConnection();
sOraConn.ConnectionString ="Provider=MSDAORA;DATA SOURCE=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST ="+sDB_Name + ")(PORT = 1521)))(CONNECT_DATA =(SERVICE_NAME = " +sDB_Name+")));PASSWORD=" + sDB_User+";PERSIST SECURITY INFO=True;USER ID=" + sDB_Passwd;
sOraConn.Open();
//构建SQL语句
OleDbCommand oraCmd = sOraConn.CreateCommand();
oraCmd.CommandText = "insert into mytb1 (contentA,contentB) values("?","测试")";
oraCmd.Parameters.Clear();
oraCmd.Parameters.Add(new OleDbParameter("@contentA", OleDbType.VarChar));
oraCmd.Parameters[0].Value = s_contentA;
oraCmd.ExecuteNonQuery();


在这段代码中,s_contentA变量是个字符串,字符串里有单位引号,如“I dont't know”。SQL语句里单引号是特殊字作符,我应该怎么处理才能使这条语句正常插入数据库里?因为我是要循环调用进行数据插入的,而字符串变量s_contentA的内容是不定的,有时会出现单引号,有时不会出现,怎么处理?

------解决方案--------------------
用个字符串代码就行,比如string str = "I don't know"

"+str+"
------解决方案--------------------
#region 执行带参数sql语句或存储过程,返回所影响的行数
/// <summary>
/// 执行带参数sql语句或存储过程,返回所影响的行数
/// </summary>
/// <param name="cmdText">带参数的sql语句和存储过程名</param>
/// <param name="cmdType">命令类型</param>
/// <param name="cmdParms">参数集合</param>
/// <returns>返回所影响的行数</returns>
public static int ExecuteNonQuery(string cmdText, CommandType cmdType, OracleParameter[] cmdParms)
{
int count;
try
{
init();
cmd = new OracleCommand();
SetCommand(cmd, cmdText, cmdType, cmdParms);
count = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
conn.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
return count;
}
#endregion


IDbDataParameter[] param = db.CreateDBParameter(type,
new string[] { "docdirid" },
new DbType[] { DbType.String);
 new object[] { model.DocDirId})

int result = db.ExecuteNonQuery(sql, CommandType.Text, param);
------解决方案--------------------
string sql = "insert into mytb1 (contentA,contentB) values(:contentA,:contentB)";
IDbDataParameter[] param = db.CreateDBParameter(type,
new string[] { "contentA", "contentB" },
new DbType[] { DbType.String, DbType.String },
new object[] { "I don't know", "测试" });

int result = db.ExecuteNonQuery(sql, CommandType.Text, param);
------解决方案--------------------
s_contentA.replace("'","''")
要测试下,意思就是把一个单引号转换为两个单引号。
这样oracle处理时就不转义了会保存一个单引号的。
------解决方案--------------------
oraCmd.CommandText = "insert into mytb1 (contentA,contentB) values("?","测试")";