简体   繁体   中英

Read output parameter value from stored procedure

My application uses a few stored procedures to insert into multiple tables fairly quickly. The PK value for the inserted rows in each table is used to insert into the next table:

Basically, my stored procedure looks something like this:

create procedure `insert_file`(out @fileid bigint, @filedata longblob, @datesaved datetime)
    begin
        insert into file(filedata, datesaved)
        values(@filedata, @datesaved);

        set @fileid = last_insert_id();
    end $$
delimiter ;

What I'm expecting is for this to output the ID for the row that was just inserted so that I can use it in my "joining" table (table that joins this file to another object - like a user or an article).

Here's my code to read this:

Int64 lastInsertID;

// db.getReader(string cmd, List<MySqlParameter>());
using (MySqlDataReader dr = db.getReader("insert_file", requiredParameters))
{
    if (dr.HasRows())
    {
        dr.Read();

        lastInsertID = dr.GetInt64("@fileid");
    }
}

While this seems to make sense in my head, I keep getting an error:

Could not find specified column in results: @fileid

Can someone help me understand what I'm doing wrong here (and how to fix it)?

  • First: You cannot read an output parameter till the reader is open.
  • Second: You can't read the output parameter using the reader because the storedprocedure use the Set statement and assign the value to the variable not to a resultset that you get back with a datareader

Probably you could try to change the last line of your storedprocedure in

 select last_insert_id();

but, then you don't need anymore the output parameter.

The correct way to use that parameter is through an ExecuteNonQuery

using (MySqlConnection cn = new MySqlConnection(GetConnectionString()))
using(MySqlCommand cmd = new MySqlCommand("insert_file", cn))
{
    cn.Open();
    // Add the required parameters here //
    cmd.ExecuteNonQuery();
    lastInsertID = Convert.ToInt32(cmd.Parameters["@fileid"].Value);
}

If there is a Row in the Rows collection, the value in the forst cell should be what you're looking for. Try this:

Int64 lastInsertID;

    // db.getReader(string cmd, List<MySqlParameter>());
    using (MySqlDataReader dr = db.getReader("insert_file", requiredParameters))
    {
        if (dr.HasRows())
        {
            dr.Read();

            lastInsertID = dr.Rows[0].Items[0];
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM