日期:2014-05-17  浏览次数:20444 次

判断用户名是否重复 asp.net access
if (Page.IsValid)
  {
  string a = username.Text;

  string sql;
  sql = "select * from userdetail where username='" + this.username.Text + "'";//建立sql查询语句
  OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("./App_Data/db1.mdb"));//建立数据库连接
  conn.Open();
  OleDbCommand cmd = new OleDbCommand(sql, conn);

  int count = Convert.ToInt32(cmd.ExecuteScalar ());
   
  if (count > 0)//如果数据中没有记录或有多条记录则抱错
  {
   
  return;
  }
  else
  {
   
   
  }

  conn.Close();
提示红色错误,说输入字符格式不正确,我该怎么转换,用的是文字

------解决方案--------------------
改成:
sql = "select count(*) from userdetail where username='" + this.username.Text + "'";//建立sql查询语句


------解决方案--------------------
另外最好用参数化SQL,直接拼不安全,容易被注入:

这样写更安全:

sql = "select count(*) from userdetail where username=?";//建立sql查询语句
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("~/App_Data/db1.mdb"));//建立数据库连接
conn.Open();
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Paramters.AddWithValue("?",this.username.Text.Trim());//添加SQL参数并给值
int count = Convert.ToInt32(cmd.ExecuteScalar());