在Oracle数据库中插入记录时应使用什么查询语法?

dgtucam1  于 2022-12-18  发布在  Oracle
关注(0)|答案(2)|浏览(186)

我是一个初学者,正在尝试用C#创建一个简单的程序,用于在Oracle数据库中插入和更新记录。我已经成功连接到数据库,但我的SQL语句出现异常,声明不支持(?)符号。为什么会出现此异常,如何修复此异常?
我的代码是:

private void btnSave_Click(object sender, EventArgs e)
{
    OracleConnection con = null;
    try
    {
        con = new OracleConnection();
        string constr = "Data source=XE; User ID=cloudester; Password=cloudester123;";
        if (con.State != ConnectionState.Open)
        {
            try
            {
                con.ConnectionString = constr;
                con.Open();
                //MessageBox.Show("Successfull connection");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception caught");
            }
        }

        if (con.State == ConnectionState.Open)
        {
            string str = "Insert into EMP_DETAIL(EmpId, Name, Age)";
            str += "values (?,?,?)";

            OracleCommand cmd = new OracleCommand();
            cmd.CommandText = Text;
            cmd.Connection = con;
            cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
            cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
            cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);

            cmd.ExecuteNonQuery();
        }
    }
    catch { ... }
}
avkwfej4

avkwfej41#

您需要为命令使用命名参数

string str = "Insert into EMP_DETAIL(EmpId, Name, Age) values (:EmpId, :Name, :Age)";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = str;  //cmd.CommandText = Text; not sure why did you use Text here
cmd.Connection = con;
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
cmd.ExecuteNonQuery();
c3frrgcw

c3frrgcw2#

如代理5566所述,并从OracleCommand.Parameters property;
CommandType.TextOracleCommand调用的SQL语句中使用命名参数时,必须在参数名前面加上冒号(:
像这样使用它们;

using(var con = new OracleConnection(constr))
using(var cmd = con.CreateCommand())
{
   cmd.CommandText = @"Insert into EMP_DETAIL(EmpId, Name, Age)
                       values (:EmpId, :Name, :Age)";
   cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
   cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
   cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
   con.Open();
   cmd.ExecuteNonQuery();
}

顺便说一下,System.Data.OracleClient在.NET 4版本中已经被标记为弃用。您可能需要使用Oracle Data Provider for .NET
作为替代方案,DataDirectDevArt也有自己的. NET Oracle提供程序。

相关问题