Insert data in AutoNumber DataType (Access Database).

Hi to all.

Normally we insert data in table.but when we need some unique identity we use primary key and make AutoNumber datatype in access database.

so when we insert data in database not add column in query of insert.

Like table name is Test and columns are Id=>AutoNumber,Name=>Text

Query for insert is ="Insert into Test (Name) Values ('TestName')"

Hear we not mention Id because Id is AutoNumber. It automatically set last id increment 1.and if we want the inserted id in database after insert query make one code "Select @@Identity";
to execute.

        public int InsertData(string sQuary)
        {
            try
            {
                //for get last inserted id
                string sQryIdentity = "Select @@Identity";
                int Id = 0;
               
               //check connection
                if (dbConnection.State != ConnectionState.Open)
                {
                    dbConnection.Open();
                }
                //create command
                OleDbCommand cmd = new OleDbCommand(sQuary);
                //set connection
                cmd.Connection = dbConnection;
                try
                {
                    //execute query
                    cmd.ExecuteNonQuery();
                    //set new command text for get identity
                    cmd.CommandText = sQryIdentity;
                    //get identity
                    Id = (int)cmd.ExecuteScalar();

                    //close connection
                    dbConnection.Close();
                    return Id;
                }
                catch (OleDbException exo)
                {
                    dbConnection.Close();
                    throw exo;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


This function return Id of inserted data in database.

Just send query string in function and return Id of data.

Thanks for read.

Comments

Popular posts from this blog

Populate combo box for month and year in c#

How to get month days count from date or month and year

CRUD Operations in win form application with access database