Connection 属性尚未初始化的问题。

来源:百度知道 编辑:UC知道 时间:2024/06/06 13:23:14
运行的时候会出错。它说是ExecuteScalar.Connection 属性尚未初始化

string userName=Request.Form["userName"].ToString();
string userPwd=Request.Form["userPwd"].ToString();
SqlConnection conn=new SqlConnection("server=.;database=Login;uid=sa;pwd=;");

conn.Open();
SqlCommand cmd=new SqlCommand("select count(*) from login where userName='"+userName+"'and userPwd='"+userPwd+"',conn");

int count=Convert.ToInt32(cmd.ExecuteScalar());
if(count >0)
{
Response.Redirect("main.aspx");
}
else
{
Response.Redirect("LoginFail.htm");
}
无法正常登陆界面。

SqlCommand cmd=new SqlCommand("select count(*) from login where userName='"+userName+"'and userPwd='"+userPwd+"'",conn);

conn后面的双引号放到逗号前面

首先检查using,也就是cs的最上面的导入文件
看看是否有这句
using System.Data.SqlClient;
如果有,请看下面的改动。

conn.Open();
SqlCommand cmd=new SqlCommand("select count(*) from login where userName='"+userName+"'and userPwd='"+userPwd+"',conn");
int count=Convert.ToInt32(cmd.ExecuteScalar());

改成

SqlCommand cmd=new SqlCommand("select count(*) from [login] where userName='"+userName+"'and userPwd='"+userPwd+"'",conn);
conn.Connection.Open();
int count=Convert.ToInt32(cmd.ExecuteScalar());
conn.Connection.Close();

Connection 初始化是由DriverManager完成的,
在装载了合适的JDBC驱动程序之后,调用DriverManager类的getConnection()方法获得一个Connection连接,然后再产生SqlConnection对象。