2014-02-19 57 views
0

我需要选择PolygonId列的最大ID。保存我的数据是这样如何在SQLite中查找Max元素?

 string sql = "create table Polygons (PolygonId int, PointId int, X double, Y double)"; 

      // Выполнение нашей команды 
      using (SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection)) 
       { 
        command.ExecuteNonQuery(); 
       } 

       int pointId = 1; 
       for (int i = 0; i < listOfCustomPolygons.Count; i++) 
        for (int j = 0; j < listOfCustomPolygons[i].listOfVertexes.Count; j++) 
        { 
         string strSQL = 
          string.Format("INSERT INTO Polygons (PolygonId,PointId,X,Y) Values ('{0}','{1}','{2}','{3}')", 
              i+1,pointId,listOfCustomPolygons[i].listOfVertexes[j].X, 
              listOfCustomPolygons[i].listOfVertexes[j].Y); 
         pointId++; 

         using (SQLiteCommand insertCommand = new SQLiteCommand(strSQL, m_dbConnection)) 
         { 
          insertCommand.ExecuteNonQuery(); 
         } 
        } 

这个我想选择多边形表和列PolygonId最大值后,但我得到了一个IndexOutOfRangeException。如何解决这个问题?

using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + openFileDialog.FileName + ";Version=3;")) 
       { 
        connection.Open(); 
        string selectMaxId = "Select Max(PolygonId) From Polygons"; 

        string selectQuery = "Select * From Polygons"; 

        SQLiteCommand selectMaxCmd = new SQLiteCommand(selectMaxId,connection); 
        SQLiteDataReader dataReader = selectMaxCmd.ExecuteReader(); 
        int maxId = Convert.ToInt32(dataReader["Select Max(PolygonId) From Polygons"]); // This is don't work! Why? 
+0

使用参数与您的查询,但真正的问题是你从读者阅读的方式,你应该阅读一些关于基本ADO.Net的文章 – Habib

回答

1

首先不创建表每次运行代码:)但你可能知道,

你键入这样的:

int maxId = Convert.ToInt32(dataReader["Select Max(PolygonId) From Polygons"]);

试试这个:

string selectMaxId = "Select Max(PolygonId) From Polygons"; 
SQLiteCommand selectMaxCmd = new SQLiteCommand(selectMaxId,connection); 
SQLiteDataReader dataReader = selectMaxCmd.ExecuteReader(); 

int maxID = -1; 

while(dataReader.read()) 
{ 
    maxID = (int)dataReader.GetValue(0); 
} 
+0

谢谢,但它没有奏效。我也有IndexOutRangeException!有什么建议么? –

+0

这没有帮助( –

0

我找到了解决方案!它应该看起来像

string selectMaxId = "Select Max(PolygonId) From Polygons"; 
SQLiteCommand selectMaxCmd = new SQLiteCommand(selectMaxId,connection); 
object val = selectMaxCmd.ExecuteScalar(); 
int maxId = int.Parse(val.ToString()); 

我希望它可以帮助谁与类似的问题面对某人)

0
//This Works for me in WPF C#: 

int MaxNum=0; 
sqliteCon.Open(); 
string Query = "SELECT MAX(Promo_No)FROM Promo_File"; 
SQLiteCommand createCommand = new SQLiteCommand(Query, sqliteCon); 
SQLiteDataReader DR = createCommand.ExecuteReader(); 
while (DR.Read()) 
{ 
    MaxNum = DR.GetInt16(0); 
} 
sqliteCon.Close();