我在程序中写SQL语句,直接取TextBox上的值插入数据库,如下:strsql = "Insert into table ( name ) values ( '" + textBox.text + "' )";一般情况下没有问题,但是如果txt框中的内容是有符号'的话,那就出错了,应该怎么处理?谢谢

解决方案 »

  1.   

    1。如果单引号必须插入数据库的话可以先将单引号替换成一个不常用的字符比如"|"或"^"
    strsql = "Insert into table ( name ) values ( '" + textBox.text.Replace("'","|") + "' )";
    取出时在替换过来
    2。不允许输入单引号
      

  2.   

    用参数方法OleDbConnection conn = new OleDbConnection();
    conn.ConnectionString = "[数据库联接串]";
    conn.Open();OleDbCommand comm = new SqlCommand();
    comm.Connection = conn;
    comm.CommandText = "Insert into table ( name ) values (@name)";
    comm.Parameters.Add("@name", SqlDbType.VarChar);
    comm.Parameters["@name"].Value = textBox.text;try
    {
        comm.ExecuteNonQuery();
    }
    cache
    {
        throw;
    }
    finally
    {    conn.Close();
        conn.Dispose();
    }
      

  3.   

    string kk=textBox.text ;
    kk=kk.Replace("'","''");
    strsql = "Insert into table ( name ) values ( '" + kk+ "' )";
      

  4.   

    拼SQL语句的时候,如果要输单引号就要一个变二个输入。
      

  5.   

    最好的就是 wlzbaby(没病真好)的解决方法了.