在 ASP.NET 中使用 SQL 适配器填充数据表时出现问题
我有一个用户名数据库表,我试图连接它来比较用户名/密码。
这是我的代码,它不起作用,我做错了什么?
DataTable dt = null;
protected void btn_Click_Login(object sender, EventArgs e)
{
string query = string.Format("SELECT * FROM Users WHERE Username='{0}' AND Password='{1}'", txtUsername.Text, txtPassword.Text);
using (SqlConnection c = new SqlConnection(ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
{
c.Open();
using (SqlDataAdapter a = new SqlDataAdapter(query, c))
{
DataTable t = new DataTable();
a.Fill(t);
}
}
if (dt.Rows.Count > 0)
{
Session["Username"] = txtUsername.Text;
Session["Password"] = txtPassword.Text;
Response.Redirect("main.aspx");
lblError.Text = "success";
}
else
{
lblError.Text = "Wrong Username/Password combination";
}
}
}
I have a username db table that I'm trying to connect with to compare the username/pass.
Here is my code, it's not working, what am I doing wrong?
DataTable dt = null;
protected void btn_Click_Login(object sender, EventArgs e)
{
string query = string.Format("SELECT * FROM Users WHERE Username='{0}' AND Password='{1}'", txtUsername.Text, txtPassword.Text);
using (SqlConnection c = new SqlConnection(ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
{
c.Open();
using (SqlDataAdapter a = new SqlDataAdapter(query, c))
{
DataTable t = new DataTable();
a.Fill(t);
}
}
if (dt.Rows.Count > 0)
{
Session["Username"] = txtUsername.Text;
Session["Password"] = txtPassword.Text;
Response.Redirect("main.aspx");
lblError.Text = "success";
}
else
{
lblError.Text = "Wrong Username/Password combination";
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您很可能使用错误的数据表来检查返回的行数。
检查数据表的 t 和 dt 实例。
most probably you are using wrong datatable to check no of rows returned.
Check for t and dt instances of datatable.
尝试创建一个 SqlCommand 来保存您的查询。
我不是 100% 确定这是你的问题,但是在我使用 ADO.NET 的时候(在 L2SQL/EF 之前,确实是黑暗的日子),我似乎记得 DataTable 和 SqlDataAdapter 的一个问题。
据我记得 - 你不能用基于原始查询字符串的 SqlDataAdapter 填充 DataTable - 你需要使用 SqlCommand。但我相信这可以通过 DataSet 来完成。
所以要么改成SqlCommand,要么改成DataSet。
Try creating a SqlCommand to hold your query.
I'm not 100% sure that's your issue, but back in the days when i used to use ADO.NET (before L2SQL/EF, dark days indeed), i seem to remember an issue with DataTable's and SqlDataAdapter.
From what i remember - you can't fill a DataTable with a SqlDataAdapter based on a raw query string - you need to use SqlCommand. But i believe this can be accomplished with DataSet.
So either change to SqlCommand, or change to DataSet.
您填写
t
:但读取
dt
:You fill
t
:but read
dt
:我决定尝试数据读取器并使其正常工作:
I decided to try the data reader and got it working:
您收到的错误是什么尚不清楚。但我觉得你们的联系是开放的,永远不会关闭。尝试
c.Close();
What error you are getting is not clear. But i feel your connection is open and is never closed. Try
c.Close();