Sunday, March 25, 2012

Check inserted data in a SQL database

Hi im having problems as im new to ASP.NET C#

i have created a button to add details into a SQL database but i want to check the details before i insert the new values from the textboxes

can anyone help...... this is what i have to insert into the database......i just want some help to compare the user name eg... if user name exists a message will appear telling the user to change a different user name

Thanks


private void Button1_Click(object sender, System.EventArgs e)
{
string connectionString = "server=\'(local)\'; trusted_connection=true; database=\'tester\'";

//System.Data.IDbConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);
System.Data.IDbConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);
conn.Open();

string commandString = "INSERT INTO Users (UserName, Password) " + "Values(@.UserName, @.Password)";

//SqlCommand dbCommand = new SqlCommand (commandString, dbconn);

System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();

//System.Data.SqlClient.SqlCommand myCmd = new System.Data.SqlClient.SqlCommand(queryString, conn);

dbCommand.CommandText = commandString;

dbCommand.Connection = conn;

SqlParameter unParam = new SqlParameter ("@.UserName", SqlDbType.NVarChar, 60);
unParam.Value = txtUser.Text;
dbCommand.Parameters.Add(unParam);
SqlParameter paParam = new SqlParameter ("@.Password", SqlDbType.NVarChar, 60);
paParam.Value = txtPassword.Text;
dbCommand.Parameters.Add(paParam);

dbCommand.ExecuteNonQuery();

conn.Close();

Response.Redirect ("WebForm1.aspx");
}

create a stored procedure, pass in userName and password to it, then make the stored procedure check if user exists and return a value.
eg:

IF NOT EXISTS (SELECT user FROM some_table WHERE <A href="http://links.10026.com/?link=mailto:user=@.userName">user=@.userName</A>)
RETURN 0 /* user doesnt exist */
ELSE
RETURN 1

then

SqlParameter ret = new SqlParameter("@.retVal", SqlDbType.Int, 4);
ret.Direction = ParameterDirection.ReturnValue;

do an ExecuteScalar on your sql command and

int status = (int)sqlCmd.Parameters["@.retVal"].Value;
if (status == 0) { // user created }
else { // failed to create user; user exists }
sql

No comments:

Post a Comment