views:

293

answers:

2

I am using SQLite C# library and as per my requirement, before going to add I am retreving the rowid of that table. It is working fine but hetting error when table is empty. Once we add any data(a row) then it’s working fine .

        mDbCon  = GetConnection();
        SQLiteCommand cmd = mDbCon.CreateCommand();
        cmd.CommandText = " SELECT MAX(rowid) FROM " + “MYTABLE”;
        cmd.CommandType = CommandType.Text;
        mDbCon.Open();
        SQLiteDataReader sqReader = cmd.ExecuteReader();
        while (sqReader.Read())
        {
            if ( sqReader.IsDBNull(0) )
            {
                max = (Int32)sqReader.GetInt32(0);
            }
        }
        mDbCon.Close();

It’s throwing exception when table “MYTABLE” don’t have any data.

+1  A: 

This should work for you.

SELECT IFNULL(MAX(RowId), 1) AS Id FROM MYTABLE
Sky Sanders
Thanks, it works.
Saurabh01
+1  A: 

try int maxRowID = Convert.Int32(cmd.ExecuteScalar());

SysAdmin
Actually, I use c# SQLite library. And it does'nt throw exception for an empty table. that is just absurd. please try it your self before commenting.
SysAdmin
-(-1)+1 Ok, on second though, not the way I would do it but not bad enough to downvote. So you get the benefit of a double upvote. Handling something like this in code instead of in the db makes me reach for a clothespin, but thats just me. Cheers.
Sky Sanders