SELECT @@IDENTITY in Access always returning 0

前端 未结 4 1722
清歌不尽
清歌不尽 2021-01-25 13:39

I have been trying to find a solution to this problem but so far nothing worked.

private void Insert()
    {
        string ConnectionStringAccess = Provider=Mic         


        
4条回答
  •  长情又很酷
    2021-01-25 14:27

    Create two different commands for your queries, execute non query then execute scalar. It will return the first column of the first row in the result set returned by the query and it should be the id you're looking for.

    private void Insert()
    {
        string ConnectionStringAccess = Provider=Microsoft.ACE.OLEDB.12.0;Data Source=###Jet OLEDB:Database Password=###;
    
        int id = -1;
    
        string Query = "INSERT INTO tblTable (EmpNo, Name) VALUES (132, 'TestName')";
        string Query2 = "SELECT @@Identity";
    
        OleDbConnection con = new OleDbConnection(ConnectionStringAccess);
    
        OleDbCommand cmd = new OleDbCommand(Query, con);
        OleDbCommand cmd2 = new OleDbCommand(Query2, con);
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            id = (int)cmd2.ExecuteScalar();
        }
        catch (Exception ex)
        {
            //log the ex
        }
        finally
        {
            con.Dispose();
            con.Close();
        }
    }
    

提交回复
热议问题