我正在尝试建立一个应该比较数据库中是否存在用户名的注册系统。
这是我的表
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
}
P.S:感谢所有想要帮助并度过愉快的一天的人:)