如何在C#中获取sql server中的max id并将其放入标签中 [英] how to get max id in sql server in C# and put it in label

查看:156
本文介绍了如何在C#中获取sql server中的max id并将其放入标签中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好









如何获得最大ID数据库表并在标签中显示

i执行此代码以获取SQL DB中的最大ID +1

SELECT MAX(patient_id)+1 FROM patient_data

并在C#中创建此代码


hello




how to get max id in database table and show it in label
i do this code to get the max id +1 in SQL DB
SELECT MAX (patient_id)+1 FROM patient_data
and make this code in C#

SqlConnection cnz = new SqlConnection(ConfigurationManager.ConnectionStrings["lap_appConnectionString"].ConnectionString);
                SqlCommand cmdzs = new SqlCommand("SELECT MAX (patient_id) FROM patient_data ", cnz);
                    cmdzs.CommandType = CommandType.Text;
                    cmdzs.Connection.Open();
                    SqlDataReader dr = cmdzs.ExecuteReader();
                    if (dr.HasRows)
                    {
                        while (dr.Read())
                        {

                            max_id_lbl.Text = dr["MAX (patient_id)"].ToString();
                        
                        }
                    }











但我在这里错误






but i error here

max_id_lbl.Text = dr["MAX (patient_id)"].ToString();



所以这里有什么问题

感谢和抱歉英语不好


so what is wrong here
thanks and sorry for bad english

推荐答案

我建​​议你每次想要从数据库中检索单个值时使用ExecuteScalar,因为它比ExecuteReader和也总是使用带有SqlConnection对象的using语句来确保它被正确处理。你可以尝试下面的代码片段。



I suggest you to use ExecuteScalar whenever you want to retrieve single value from database as it perform better than ExecuteReader and also always use using statement with SqlConnection object to make sure it get disposed properly. You can try below code snippet.

string conStr = ConfigurationManager.ConnectionStrings["lap_appConnectionString"].ConnectionString;
          using (SqlConnection cnz = new SqlConnection(conStr))
          {
              SqlCommand cmdzs = new SqlCommand("SELECT MAX (patient_id) as max_patient_id FROM patient_data ", cnz);
              cmdzs.CommandType = CommandType.Text;
              cnz.Open();
              max_id_lbl.Text = cmdzs.ExecuteScalar().ToString();
          }


试试这样它会起作用

try like this it will work
SqlConnection cnz = new SqlConnection(ConfigurationManager.ConnectionStrings["lap_appConnectionString"].ConnectionString);
                SqlCommand cmdzs = new SqlCommand("SELECT MAX (patient_id) FROM patient_data ", cnz);
                    cmdzs.CommandType = CommandType.Text;
                    cmdzs.Connection.Open();
                    SqlDataReader dr = cmdzs.ExecuteReader();
                    if (dr.HasRows)
                    {
                        while (dr.Read())
                        {
 
                            max_id_lbl.Text = dr[0].ToString();
                        
                        }
                    }


这篇关于如何在C#中获取sql server中的max id并将其放入标签中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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