在标签中调用SQL查询 [英] Call SQL Query in lable

查看:61
本文介绍了在标签中调用SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我.

我写了这段代码,但是没有用.

我的错误是什么,正确的代码是什么?

Please help me.

I wrote this code but it doesn''t work.

What is my mistake and what is the correct code ?

protected void Page_Load(object sender, EventArgs e) 
{ 
  SqlCommand cmd = new SqlCommand(); 
  cmd.Connection = new SqlConnection(Class1.CnnStr);

  cmd.CommandText = "SELECT MAX(Code) FROM Customer"; 
  cmd.Connection.Open();   
  cmd.Parameters.AddWithValue(Code_lbl.Text,"@MAX(Code)"+1);   
  cmd.ExecuteNonQuery(); 
 }

推荐答案

这是行不通的,因为它是从各种来源汇集而来的,没有太在意您在做什么.

That doesn''t work because it is thrown together from a variety of sources, without thinking too hard what you are doing.

SELECT MAX(Code) from Customer

没有任何参数,因此尝试添加它们将无济于事.
即使这样做,字符串的值加上数字1的值是多少?答案:末尾带有"1"的字符串.因此,您的代码

Does not have any parameters so trying to add them is not going to help.
Even if it did, what is the value of a string plus the number one? Answer: a string with a "1" on the end. So your code

"@MAX(Code)"+1

实际上与

"@MAX(Code)1"

您的Label.Text几乎可以肯定,即使实际上有任何内容,SQL语句中也不包含参数的名称.

Your Label.Text almost certainly doesn''t contain the name of a parameter in your SQL statement even if you actually had any.

cmd.ExecuteNonQuery();

使用SELECT sql命令浪费时间,因为SELECT命令不会影响表中的任何行,它只会根据选择条件返回它们.除非它确实返回了任何行,否则您都将其丢弃然后丢弃,因为ExecuteNonQuery返回了受影响的行数.

如果没有更好地描述您实际上想做什么,我就无法告诉您问题出在哪里,因为一切都错了-它根本没有做任何有用的事情,因此我无法告诉您什么您正在尝试做!

Is a waste of time with a SELECT sql command because a SELECT command does not affect any rows in the table, it just returns them based on the selection criteria. Except that even if it did return any rows, you then throw then away, because ExecuteNonQuery returns the number of rows affected.

Without a better description of what you are actually trying to do, I can''t tell you what is wrong with it, because everything is wrong - it doesn''t do anything useful at all, so I can''t tell what you were trying to do!


格里夫所说的话.

摆脱cmd.Parameters.您没有参数.

同样,您的SQL查询从数据库返回一个离散(单个)值.您要使用ExecuteScalar.

我不会为您编写代码,在线上有很多参考. Google:"ExecuteScalar".
What Griff said.

Get rid of the cmd.Parameters. You have no parameters.

Also, your SQL query returns a discrete (single) value from the database. You want to use ExecuteScalar.

I am not going to code it for you, there are numerous references online. Google: "ExecuteScalar".


这篇关于在标签中调用SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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