数据库
首页 > 数据库> > 我应该使用哪种查询语法在Oracle数据库中插入记录?

我应该使用哪种查询语法在Oracle数据库中插入记录?

作者:互联网

我是一个初学者,试图用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 { ... }
}

解决方法:

您需要为命令使用named参数

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();

标签:query-parameters,oracle,sql-insert,c
来源: https://codeday.me/bug/20191028/1952377.html