Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 循环c的SELECT语句中的WHERE变量_C#_Sql_Webforms - Fatal编程技术网

C# 循环c的SELECT语句中的WHERE变量

C# 循环c的SELECT语句中的WHERE变量,c#,sql,webforms,C#,Sql,Webforms,因此,我试图创建一个名为shoutout的区域,当前用户可以在其中查看shoutout,基本上是来自shoutout表的消息,这些消息来自与他/她的朋友 所以,我首先将当前用户的所有朋友放入一个名为currentuserfriends的数组中,然后我希望从shoutout表中选择message,其中username=currentuserfriends中的所有用户 但是我不知道如何在select语句中循环 我不想做这样的事情 string getuserfriendlist=从朋友中选择朋友,其

因此,我试图创建一个名为shoutout的区域,当前用户可以在其中查看shoutout,基本上是来自shoutout表的消息,这些消息来自与他/她的朋友

所以,我首先将当前用户的所有朋友放入一个名为currentuserfriends的数组中,然后我希望从shoutout表中选择message,其中username=currentuserfriends中的所有用户

但是我不知道如何在select语句中循环

我不想做这样的事情

string getuserfriendlist=从朋友中选择朋友,其中用户名='+currentuserfriends[0]+'

并手动增加currentuserfriends[0]。有没有一种方法可以循环currentuserfriends,直到在一个select语句中结束?谢谢

朋友桌

用户名|朋友

叫喊台

用户名|消息|日期时间

代码:


在数组上使用foreach循环,然后生成SQL查询

有没有一种方法可以循环currentuserfriends直到在一个 选择语句


是的,有。可以这样做。

首先使用以下代码将数组设置为逗号分隔的字符串

string idString = String.Join(",",currentuserfriends);
然后,使用下面的sql语句

SELECT friend FROM friend WHERE username in ("+idstring+");
可以使用列表而不是数组。在这种情况下,您可以执行以下操作:

var currentuserfriends = new List<string>();

while (drb.Read())
{
    currentuserfriends.Add(drb["friend"].ToString())
}

避免您手工处理SQL查询,并直接防止您的查询进行SQL注入,因为您当前的查询容易受到SQL注入的攻击。

我想报告一个错误,我创建了一个用户帐户,现在您的网站停止工作。我的用户名是';升降台呼喊;-请注意使用SqlParameters,做一个搜索。这个网站上有很多关于它的问题。sql注入让我开心!就主题而言,这可能会解决你的问题。编辑:另一个附带问题,9999大小的数组是什么?为什么不使用列表呢?@ScottChamberlain:我认为你在这里遇到的问题最少。真正的危险是有人接管了你的服务器,或者你不知道。@Steven是的,但是在评论的空间里,放置表格是最容易表达观点的,不过谢谢你的链接,我以后会用它作为一个很好的例子。
var currentuserfriends = new List<string>();

while (drb.Read())
{
    currentuserfriends.Add(drb["friend"].ToString())
}
var db = new ObjectContext();

string[] currentuserfriends = (
    from friend in db.Friends
    where friend.Username == currentuser
    select friend.Name)
    .ToArray();