使用 C# 将记录插入 Oracle 数据库时出错 - 由于对象的当前状态,操作无效

Error on while inserting record to Oracle database using C# - Operation is not valid due to the current state of the object

OracleConnection 连接; conn = new OracleConnection();

        conn.ConnectionString = "DATA SOURCE=xyz;PASSWORD=xyz;PERSIST SECURITY INFO=True;USER ID=xyz";
        conn.Open();
        Console.WriteLine("Connected to oracle" + "  " + conn.ServerVersion);

        OracleCommand cmd = new OracleCommand();

        cmd.CommandText = "Insert into Users values('test',123,'test','entry','12345')";

        int rowsUpdated = cmd.ExecuteNonQuery();
        if (rowsUpdated == 0)
            Console.WriteLine("Record not inserted");
        else
            Console.WriteLine("Successfully record inserted!"); 

        conn.Close();
        conn.Dispose();

出现以下错误: 由于对象的当前状态,操作无效

我遇到过同样的问题。

您可能正在使用单独的方法:

using (oracleConnection = new OracleConnection(oracleConnectionString))

您应该将其更改为:

oracleConnection = new OracleConnection(oracleConnectionString);

例如:

    public void Conn() {
        string oracleConnectionString = "User Id=" + oracleUser + "; Password=" + oraclePassword + "; Data Source=" + oracleDatabase;
        //using (oracleConnection = new OracleConnection(oracleConnectionString))
        oracleConnection = new OracleConnection(oracleConnectionString);
        try
        {
            oracleConnection.Open();
            Console.WriteLine(oracleConnection.ServerVersion);
            Console.ReadKey();
            OracleGlobalization oracleSession = oracleConnection.GetSessionInfo();
            oracleSession.DateFormat = "dd-mm-yyyy hh24:mi:ss";
            oracleConnection.SetSessionInfo(oracleSession);
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message);
            Console.WriteLine(ex.Message);
            Console.ReadKey();
        }
    }

并这样称呼它:

    public void Insert()
    {
        Conn();
        // other stuff here
    }