Search code examples
c#oracleoraclecommand

Why does cmd.executeNonQuery() throw ManagedDataAccess.Client.OracleException?


I tried to write this very simple code to find the problem without any variables, but I can't. If I copy the same query in the sqldeveloper it works. The ServerVersion still shows up correctly in the messagebox.

The function is called like: new Dal().testCon();

public OracleConnection con;

public Dal()
{
    con = new OracleConnection();
    con.ConnectionString = "User Id=satan;Password=666;Data Source=MyDB";
}

public void testCon()
{
    con.Open();
    MessageBox.Show(con.ServerVersion);
    OracleCommand cmd = new OracleCommand("insert into myuser values(1,'Pornstar','xxx',18);", con);
    cmd.ExecuteNonQuery();
    con.Close();
}

Stack-trace


Solution

  • The error is caused by including the semicolon in the SQL. Change your query string to "insert into myuser values(1,'Pornstar','xxx',18)".

    I'd also recommend moving the connection into the testCon method, like so:

    private const string ConnectionString = "User Id=satan;Password=666;Data Source=MyDB";
    
    public Dal()
    {
    }
    
    public void testCon()
    {
        using (OracleConnection connection = new OracleConnection(ConnectionString))
        {
            OracleCommand cmd = new OracleCommand("insert into myuser values(1,'Pornstar','xxx',18)", connection);
            cmd.Connection.Open();
            MessageBox.Show(connection.ServerVersion);
            cmd.ExecuteNonQuery();
        }
    }