Visual C#SQL数据库选择查询到变量 [英] Visual C# SQL Database Select Query into Variables

查看:169
本文介绍了Visual C#SQL数据库选择查询到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计们,

我正在构建一个查询,它将根据值'RentDue'从数据库中选择数据。我想获得相应的值'id'。鉴于我的代码如下,这将如何实现?



  string  sql =  来自Rooms的SELECT(ID,RentDue) +  其中RentDue =' +  22  +  '); 
SqlCommand execsql = new SqlCommand(sql,cn);
cn.Open();





另外,我该如何处理多个结果?获得ID后,我会将其附加到RichTextView,我希望每次查询运行时都会有多个结果。



谢谢!

解决方案

0)不要对SQL语句使用字符串连接;使用参数化查询。

1)如果您选择单个值,您可以使用ExecuteScalar

2)如果您选择多个值,那么您将需要其他东西 - - 也许是ExecuteReader。



  string  sql =  来自RentDue = @rentdue的房间的SELECT ID ; 
SqlCommand execsql = new SqlCommand(sql,cn);
execsql.Parameters.AddWithValue( @ rentdue 22 );
cn.Open();

... // 你想用它做什么?


Hey guys,
I am building a query that will select data from the database based on the value 'RentDue'. I am trying to get the corresponding value 'id'. Given my code below, how will this be possible?

string sql = "SELECT  (ID, RentDue) from Rooms " + "where RentDue = '" + 22 + "')";
                SqlCommand execsql = new SqlCommand(sql, cn);
                cn.Open();



Also, how can I handle multiple results? Once I have obtained the ID, I will appending it to a RichTextView, and I expect there will be more than one result every time the query runs.

Thank you!

解决方案

0) Don't use string concatenation to for an SQL statement; use a parameterized query.
1) If you are selecting a single value you can use ExecuteScalar
2) If you are selecting multiple values, then you will need something else -- perhaps ExecuteReader.

string sql = "SELECT ID from Rooms where RentDue = @rentdue";
SqlCommand execsql = new SqlCommand(sql, cn);
execsql.Parameters.AddWithValue ( "@rentdue" , 22 ) ;
cn.Open();

... // What do you want to do with it?


这篇关于Visual C#SQL数据库选择查询到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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