【发布时间】:2021-11-14 22:59:29
【问题描述】:
我正在尝试将用于凭证 ID 和凭证金额的 sql 数据存储到一个变量中,并通过单击按钮将其显示到标签中。
protected void Button1_Click(object sender, EventArgs e)
{
string voucherId = String.Empty;
string voucherAmount = String.Empty;
string queryVoucherId = "select voucherid from ReturnForm where email = '" + Session["username"] + "';";
string queryVoucherAmount = "select voucheramount from ReturnForm where email = '" + Session["username"] + "';";
int index = 0;
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherId, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherId = reader[index].ToString();
index++;
}
}
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherAmount, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherAmount = reader[index].ToString();
index++;
}
}
if (txtVoucher.Text == voucherId)
{
Label3.Visible = true;
Label3.Text = voucherAmount;
}
}
当我点击按钮时,它给我一个错误,提示索引超出范围。
【问题讨论】:
-
开始第二次查询时需要将
index重置为0 -
首先 - 您可以在 single 查询中执行此操作,方法是在
SELECT语句中选择两个必需的列。更重要的是:永远不要这样写 SQL!不要不将您的 SQL 代码与参数值连接在一起 - 使用 参数化查询 - 总是 - 没有例外。您对 #1 Internet 漏洞持开放态度 - SQL 注入 ...
标签: c# asp.net sql-server webforms