生成ID号时无法从表中读取数据 [英] Unable to read data from table while generating ID number

查看:69
本文介绍了生成ID号时无法从表中读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友们!

我想从SQL Server使用ASP.net + C#生成ID.我遇到这些类型的错误
在没有数据的情况下无效的读取尝试"

当我在表中有数据时.

经过一些代码修改后,它无法在表中插入我为ID生成的值,而它仅插入0.

hi friends!!

i m trying to generate id using ASP.net + c# from sql server. I m getting these type of errors
"Invalid attempt to read when no data present"

while i have data in the table.

AFter some modification in code it is not able to insert the value i generate for ID in the table rather it is inserting 0 only.

 <pre lang="cs"> int id =0;
protected void Button1_Click(object sender, EventArgs e)
    {
        cm = new SqlCommand("select MAX(id) from login",cn);
        dr = cm.ExecuteReader();
        if(dr.Read()==false)
        id = Convert.ToInt32(dr[0].ToString());
        if (id == 0)
        {
            id = 1001;
            TextBox4.Text = id.ToString();
        }
        else {
            TextBox4.Text = dr[0].ToString();
            id = Convert.ToInt32(dr[0].ToString()) + 1;
        }
        dr.Close();
        TextBox3.Text = "My id is : "+id.ToString();
    }



我假设用户将提供一个空白表,他将在其中插入实时数据,然后它将生成ID号1001、1002、1003 ... n(我不想使用自动递增)
将数据插入表的代码



i have assumption that user will have provide blank table where he will insert his live data then it should generate id number 1001, 1002, 1003 ... n ( i dont want to use auto increment)
code for insertion of data into table

<pre lang="cs">protected void Button3_Click(object sender, EventArgs e)
   {
       cm = new SqlCommand("insert into login values(''" + TextBox2.Text + "'',''" + TextBox1.Text + "'',''" + id.ToString() + "'')", cn);
       cm.ExecuteNonQuery();
   }



请给我一些提示,为什么它会产生这样的错误



Plz give me your hints why it is generating such error

推荐答案

在没有数据的情况下无效的读取尝试

尝试更改此内容:

Invalid attempt to read when no data present

Try changing this:

if (dr.Read() == false)



对此



to this

if (dr.Read())



如果读者不阅读,则您当前的代码正在尝试执行某些操作.这与您实际想要的相反.



Your current code is trying to do something if the reader does NOT read. that''s backwards from what you actually want.


尝试使用以下代码:

try use this code:

cm = new SqlCommand("select isnull(MAX(id),0) from login",cn);        
dr = cm.ExecuteReader();                  
if(dr.Read())                                                     
{
     id = Convert.ToInt32(dr[0].ToString());                                                
}


它仍在数据库中插入0 ...我不明白为什么它在dbo.table中取0.
it is still inserting 0 in the database... i could not understand why it is taking 0 in the dbo.table


这篇关于生成ID号时无法从表中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆