请.NET高手帮忙----数据库连接

来源:百度知道 编辑:UC知道 时间:2024/05/29 03:18:14
这是我的登录代码
protected void Button1_Click(object sender, EventArgs e)
{
string strConn = ("Server=(local); Database=itzc; uid=sa;pwd=sa;");
string strCmd = ("select * from Staff_login where S_ID = '" + S_ID.Text + "' and Sl_pwd= '" + Sl_pwd.Text + " '");
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = strConn;
SqlCommand myCommand = new SqlCommand(strCmd, myConnection);
myCommand.Connection.Open();
int flag = System.Convert.ToInt32(myCommand.ExecuteScalar());
myCommand.Connection.Close();
myConnection.Close();
if (S_ID.Text == "")
{
Response.Redirect("<script>alert('用户名不能为空');</script>");
}
else if (Sl_pwd.Text == " ")
{
Resp

好像你的本意是如果有所差的语句 在数据库里有值的话 就通过登陆对吧
可是你用错方法了ExecuteScalar()返回的是第一行第一列的值 不是多少条记录
第一行第一列是int型的话 这个就没错 反之如果是其他类型的 不知道Convert.ToInt32 会转换成什么数字 如果是字符串 那肯定是非负数
自然flag>0

你可以这样做
你原来的查询语句是这样的吧
select * from Staff_login where S_ID = ? and Sl_pwd= ?
你改成这样
select count(*) from Staff_login where S_ID = ? and Sl_pwd= ?
这样出来的就是有多少条数

int flag = System.Convert.ToInt32(myCommand.ExecuteScalar());
这句加断点调试