1

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.

CrazyC
  • 1,840
  • 6
  • 39
  • 60
  • @Saurabh - Welcome to StackOverflow - The way things work here is that you ask questions and when someone takes time out of their busy day to help you, you click the check mark next to the best answer and maybe even upvote the answer by clicking the up arrow. This does two things: 1) It gives the answerer the only reward they get for helping - reputation, and 2) helps others who find this question determine the solution. Does that make sense? – Sky Sanders Apr 03 '10 at 18:27

2 Answers2

2

This should work for you.

SELECT IFNULL(MAX(RowId), 1) AS Id FROM MYTABLE
Sky Sanders
  • 36,396
  • 8
  • 69
  • 90
1

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

Sky Sanders
  • 36,396
  • 8
  • 69
  • 90
SysAdmin
  • 5,455
  • 8
  • 33
  • 34
  • 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 Apr 02 '10 at 02:41
  • -(-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 Apr 02 '10 at 12:20