各位大虾,我这里遇到一个关于asp.net和sql的简单问题,错误提示为:关键字 'key' 附近有语法错误。求解脱

我的代码为:
using System;using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Styles_login : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
}
static void main(string[] args) {
}
protected void Button1_Click(object sender, EventArgs e) {
string userName=this.TextBox1.Text;
string userPwd = this.TextBox2.Text;
string connStr = "server=.;uid=sa;pwd=123;dataBase=student";
SqlConnection conn = new SqlConnection(connStr);
try
{

conn.Open();
string sql = "SELECT username,key FROM student WHERE username = '" + userName + "'and key ='" + userPwd + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
int result = cmd.ExecuteNonQuery();
if (result > 0) {
TextBox3.Text = "登陆成功";
}
else
{
TextBox3.Text = "登陆失败";
}
}
catch (Exception ex)
{
TextBox3.Text = ex.Message;
}
finally
{
conn.Close();
}
}}

运行后的图片为

这个key是student表中的一个字段么?
这里之所以会出错,是因为key是sql server中的一个关键字,如果你也用了key做为字段名,那么可以写成[key],加个中括号就好了:
string sql = "SELECT username,[key] FROM student WHERE username = '" + userName + "'and [key] ='" + userPwd + "'";
温馨提示:答案为网友推荐,仅供参考
相似回答