获取查询出来的值

写代码养猫 2008-04-05 02:17:57
string name = this.TextBox1.text;

string sql = "select IndustryId from TABLE1 where IndustryName='"+ name +"'";

如何才能取出 IndustryId并存放到一个定义的变量里呢 大侠指点!!(假如我定义一个 int id; 怎么把查询出来的IndustryId存放到id里边呢??)

急!
...全文
165 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
agilis 2008-04-06
  • 打赏
  • 举报
回复
应先判断一下是否没有记录或者字段值为DBNull
libraworm 2008-04-05
  • 打赏
  • 举报
回复
学校不该教C#,应该教C++。
C#把啥都封装了,学了C#的大把人还是啥都不懂。

毕业久了,你就会知道大学课本教的并不是完全脱离实际一点没用。
tomiehu 2008-04-05
  • 打赏
  • 举报
回复
SqlCommand.ExecuteScalar() 返回的是 object 你直接

name = (string)SqlCommand.ExecuteScalar();

试试看
我在地球 2008-04-05
  • 打赏
  • 举报
回复
SQL 查询出来的是一个记录集 不一定是只有一条记录呀
放在 table 或 reader 里头 ,自己用程序控制咯
Plife472 2008-04-05
  • 打赏
  • 举报
回复
如果获取单个值的话使用,SqlCommand.ExecuteScalar();性能更好
badtank 2008-04-05
  • 打赏
  • 举报
回复
跟踪看一下reader里面的值。reader["IndustryId"].
写代码养猫 2008-04-05
  • 打赏
  • 举报
回复
这样好象不行哦.. 运行到 id = Convert.ToString(reader["IndustryId"]);那就出问题了.
就弹出一个对话框 显示 "Industry ";

badtank 2008-04-05
  • 打赏
  • 举报
回复
string connstring = "";
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
string name = this.TextBox1.text;

string sql = "select IndustryId from TABLE1 where IndustryName='"+ name +"'";

string id;//要存储的ID变量
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.Read()) {
id = Convert.ToString(reader["IndustryId"]);
}
conn.Close();
conn.Dispose();
写代码养猫 2008-04-05
  • 打赏
  • 举报
回复
学校学过 .. 都忘记了哈哈. 给出详细代码好吗??
badtank 2008-04-05
  • 打赏
  • 举报
回复
先将运行结果放在DataSet 或DataReader中,然后再将DataSet 或Reader中的值给id赋值。
楼主应仔细学习一下ado.net的基础知识。

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧