日期:2014-05-18  浏览次数:21356 次

连不上mysql数据库(未将对象引用到对象的实例
public class User:
  SRMS.IDataAccessLayer.IUser
  {
  #region IUser 成员
  string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
   
   
   
  private const string ValidateUserSQL
  = "select UserId from users where UserName=@username and Password=@password";

  //定义参数
  private const string usernameParameter = "@username";
  private const string passwordParameter = "@password";


  public bool ValidateUser(string username, string password)
  {
  //定义参数对象
  MySqlParameter pName = new MySqlParameter(usernameParameter, MySqlDbType.VarChar, 50);
  MySqlParameter pPwd = new MySqlParameter(passwordParameter, MySqlDbType.VarChar, 50);

  //为对象赋值
  pName.Value = username;
  pPwd.Value = password;

  //执行sql语句
  using (MySqlConnection connection = new MySqlConnection(connectionString))
  {
  MySqlCommand command = new MySqlCommand(ValidateUserSQL, connection);
  connection.Open();

  command.Parameters.Add("@username", MySqlDbType.VarChar).Value = username;
  command.Parameters.Add("@password", MySqlDbType.VarChar).Value = password;

  object result= command.ExecuteScalar();

  //如果有查到,返回值就不为null
  return result != null;

  }

   
  }


//////////////////////////////////////////我用的是MySql数据库
  string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ConnectionString; 错误提示:未将对象引用到对象的实例

配置文件时这样写的:
<connectionStrings>
<add name="conn" connectionString="host=127.0.0.1;database=mysrms;uid=root;pwd=123;"/>
</connectionStrings>
 

------解决方案--------------------
你数据库连接字符串写的有问题
这样写

<connectionStrings>
<add name="conn" 
connectionString="server=localhost;User Id=root;password=123;Persist Security Info=True;database=mysrms"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>