我正在尝试做一个注册系统,该系统应该比较数据库中是否存在用户名。
这是我的桌子
CREATE TABLE [dbo].[Registros] (
[ID_Utilizador] INT IDENTITY (1, 1) NOT NULL,
[NomeUtilizador] VARCHAR (20) NOT NULL,
[PasseUtilizador] VARCHAR (20) NOT NULL,
[EmailUtilizador] VARCHAR (50) NOT NULL,
[NomeCompletoUtilizador] VARCHAR (50) NOT NULL,
[PaisUtilizador] CHAR (10) NOT NULL,
PRIMARY KEY CLUSTERED ([ID_Utilizador] ASC)
);
这应该验证用户是否出于某种原因存在于“NomeUtilizador”列中..但它不适用于
if (IsPostBack)
{
SqlConnection conexao = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrosConnectionString"].ConnectionString);
conexao.Open();
string cmdstr = "SELECT COUNT(*) FROM Registros WHERE NomeUtilizador ='"+TBusername.Text+"'";
SqlCommand UserExists= new SqlCommand(cmdstr, conexao);
int temp = Convert.ToInt32(UserExists.ExecuteScalar().ToString());
conexao.Close();
if (temp ==1)
{
Response.Write(" UsernameAlreadyExists! <br /> choose another ");
}
}
}
解决方案
protected void BTsubmeter_Click(object sender, EventArgs e)
{
SqlDataReader reader = null;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrosConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("select * from Table where NomeUtilizador=@NomeUtilizador", conn);
cmd.Parameters.AddWithValue("@NomeUtilizador", TBusername.Text);
reader = cmd.ExecuteReader();
if (reader != null && reader.HasRows)
{
//if username is matching
Response.Write(" Username Exists! <br />Choose another ");
conn.Close();
}
else
{
//if not matching do something
}
PS:感谢所有试图提供帮助并度过美好一天的人:)