简体   繁体   English

数据库错误:位置0没有行

[英]Database Error: There is no row at position 0

I believe this question was asked several months back, but i believe my situation is different and the same rules may not apply. 我相信这个问题是在几个月前被问到的,但我相信我的情况有所不同,同样的规则也许不适用。

Everytime I execute this method that same error pops up. 每次我执行此方法时都会弹出相同的错误。 There is no row at position 0. If I change [0] to [1] or [15]; 位置0没有行。如果我将[0]改为[1]或[15]; There is no row at [1] and etc. Could this mean that my database isnt even connecting? [1]等处没有行。这是否意味着我的数据库连接都没有? Should I write some kind of if statement to determine to check if the rows are even there? 我应该写一些if语句来确定行是否在那里?

    public bool UpdateOrderToShipped(string order)
{
    orderNumber = order;
    string batch = ConfigurationManager.AppSettings["SuccessfulOrderBatch"];
    string statement = "UPDATE SOP10100 SET BACHNUMB = '"+ batch +"' WHERE SOPNUMBE = @SOPNUMBE";
    SqlCommand comm = new SqlCommand(statement, connectionPCI);
    comm.Parameters.Add("SOPNUMBE", orderNumber);
    try
    {
        comm.Connection.Open();
        comm.ExecuteNonQuery();
        comm.Connection.Close();
    }
    catch(Exception e)
    {
        comm.Connection.Close();
        KaplanFTP.errorMsg = "Database error: " + e.Message;
    }

    statement = "SELECT SOPTYPE FROM SOP10100 WHERE SOPNUMBE = @SOPNUMBE";
    comm.CommandText = statement;
    SqlDataAdapter da = new SqlDataAdapter(comm);
    DataTable dt = new DataTable();
    da.Fill(dt);
    soptype = dt.Rows[0]["SOPTYPE"].ToString();    //errror here

    return true;
}

This is very simple ... it means that no results were returned from your query. 这很简单......这意味着您的查询没有返回任何结果。 You always have to code defensively and check to see if the Rows array has any items in it before trying to index into it. 您始终必须进行防御性编码并在尝试索引之前检查Rows数组中是否包含任何项目。 Something like: 就像是:

if (dt.Rows.Count > 0)
    soptype = dt.Rows[0]["SOPTYPE"].ToString();
else
    somethingWentWrong();
for (int i = 0; i <= dt.rows.count; i++) { // do something till rows in DT }

you might have data in the table but I think the connection closes after the first query. 您可能在表中有数据但我认为连接在第一次查询后关闭。 try opening the connection again. 尝试再次打开连接。 Also you have string concatenation in the first SQL query, which isn't a good practice. 你在第一个SQL查询中也有字符串连接,这不是一个好习惯。 try using block instead of try.. catch, just for a better code. 尝试使用块而不是try .. catch,只是为了更好的代码。 And as Joel suggested, use a check 正如乔尔建议的那样,使用支票

I was having the same problem, then I realized that my first column was not integer-based. 我遇到了同样的问题,然后我意识到我的第一列不是基于整数的。 So when I edited the first I faced the same error. 所以当我编辑第一个时,我遇到了同样的错误。

So, my suggestion is either not to edit the first column or make the first column an ID column in which case you don't have to edit anything. 因此,我的建议是不要编辑第一列或将第一列设为ID列,在这种情况下您不必编辑任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM