本文介绍了Sqlite.net ...获取最后一个插入ID ...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正准备在下周接受C#的求职面试...以为我会写一个小应用程序来管理我的Tablature/Lyrics集合...我认为应该很简单...我在从sqlite数据库中检索最后一个插入ID时遇到问题...插入工作正常,但是我似乎无法使后续查询正常工作...代码在下面...

I''m trying to bone up on C# for a job interview I have this coming week... thought I''d write a little application to manage my Tablature/Lyrics collection... should be pretty simple me thinks... I''m having problems retrieving the last insert id from an sqlite database... the insert IS working, but I cannot seem to get the follow up query to work... the code is below...

           String connString = "Data Source=" + Properties.Resources.dataSource;
                SQLiteConnection conn = new SQLiteConnection(connString);

                SQLiteCommand cmd = new SQLiteCommand(conn);

                cmd.CommandText = "insert into lyrics (song, lyrics) values (@title, @words);";
                cmd.Parameters.AddWithValue("@title", _title);
                cmd.Parameters.AddWithValue("@words", _words);

                SQLiteCommand cmd_id = new SQLiteCommand(conn);
                cmd_id.CommandText = "select last_insert_rowid() as id from lyrics";

                conn.Open();
                cmd.ExecuteNonQuery();

<big>                _id = (int) cmd_id.ExecuteScalar(); <--- the code gags on this telling me I am not getting a valid value!!!
</big>                //cmd_id.
                conn.Close();
                conn.Dispose();
                return true;



任何建议将不胜感激...我已经遍及Google了(这是我所拥有的代码的来源)...

谢谢

Michael



Any suggestions would be appreciated... I''ve been all over Google with this (which is where I got the code that I have)...

Thanks

Michael

推荐答案

object val = cmd_id.ExecuteScalar();
_id = (int)val; // Set a breakpoint here, and examine the contents of val



也许您正在返回DbNull值,表明您的查询未正确执行.也许last_insert_rowid()返回的值不是int类型.



Maybe you''re getting back a DbNull value, indicating that your query didn''t execute properly. Or perhaps the value that is being returned by last_insert_rowid() isn''t of type int.


cmd_id.CommandText = "select last_insert_rowid() as id from lyrics";
conn.Open();
cmd.ExecuteNonQuery();
System.Object temp = cmd_id.ExecuteScalar();
_id = int.Parse (temp.ToString());



有没有一种更整洁",更干净"的转换方法?

谢谢
Michael



Is there a ''neater'',''cleaner'' way to do that conversion?

Thanks
Michael



这篇关于Sqlite.net ...获取最后一个插入ID ...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 06:40