【问题标题】:How to read 2 commands without closing the first one?如何在不关闭第一个命令的情况下读取 2 个命令?
【发布时间】:2019-03-23 20:54:34
【问题描述】:

我正在尝试检查用户名或电子邮件是否被占用。但是,我想单独检查它们。第一个用户名,第二个电子邮件。我是初学者,所以我不知道如何编写此代码。当我检查用户名是否被占用时,没关系。但在检查电子邮件后,它给出了一个错误,并说关闭第一个 SQL 命令。

那么我该怎么做呢?如何在不关闭第一个 SQL 命令的情况下读取 2 个 SQL 命令?

// Checking if username is taken
var command = new SqlCommand("SELECT * FROM kullanicilar WHERE kullaniciAdi = '<username text>' , 
yourConnection);
var reader = command.ExecuteReader();

// Checking if email is taken
var command = new SqlCommand("SELECT * FROM kullanicilar WHERE [Mail Adresi] = '<mail address text>', 
yourConnection)
var reader2 = command.ExecuteReader();

【问题讨论】:

  • 请参阅 How to Ask 帮助页面和 The perfect question Jon Skeet 的博客文章。如果没有看到您的原始代码,我们将不知道如何对您现有的代码库进行更改。请发minimal reproducible example,并详细说明需要修改的地方。
  • 使用 存储过程 并且顺便说一句,停止将代码作为图像发布

标签: c# sql ado.net


【解决方案1】:
// Check if username is taken
var command = new SqlCommand("SELECT * FROM YourTable WHERE userName=" userName , 
yourConnection);
var reader = command.ExecuteReader();

// Check if email is taken
var command = new SqlCommand("SELECT * FROM YourTable WHERE email=" email, 
yourConnection)
command.ExecuteNonQuery();

【讨论】:

  • 我在 if else 语句块中这样做,所以这没有帮助
【解决方案2】:

首先,我不确定你为什么坚持必须在两个单独的查询中找到结果,并且在执行时也没有关闭第一个命令(如果这就是你的意思是“不关闭第一个”)第二个。

对我来说,您似乎想知道数据库中是否已经存在姓名和电子邮件,如果存在,它们是由同一个人(在数据库中的同一记录中找到)还是由不同的人(在不同记录中找到)采取)。

您可以通过执行一个查询来实现此目的。您可能会返回多条记录,并且对于每条记录,第三列 match_type 将阐明类型。

select kullaniciAdi, [Mail Adresi], 'BOTH' as match_type  from kullanicilar 
where kullaniciAdi = '<username text>' and [Mail Adresi] = '<mail address text>'
union 
select kullaniciAdi, [Mail Adresi], 'ONLY_USER' as match_type  from kullanicilar 
where kullaniciAdi = '<username text>' and [Mail Adresi] <> '<mail address text>'
union
select kullaniciAdi, [Mail Adresi], 'ONLY_MAIL' as match_type  from kullanicilar 
where kullaniciAdi <> '<username text>' and [Mail Adresi] = '<mail address text>'

注意查询中的表和/或列名称可能有拼写错误,因为它很容易在查看图像时输入错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多