Check if username existed in SQLExpress - c#

Error shows : ExecuteScalar: Connection property has not been
initialized and exists = (int)cmd.ExecuteScalar() > 0;
bool exists = false;
using (SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName"))
{
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
if (exists)
{
lblUserName.Text = "This username has been used by another user.";
}
else
{
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO Users (UserID,FName, LName, PhoneNo, Address, Email, UserName, Password, Points, Role) VALUES (#UserID,#FName, #LName, #PhoneNo, #Address, #Email, #UserName, #Password, #Points, #Role)");
try
{
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#UserID", UserID);
cmd.Parameters.AddWithValue("#FName", tbFName.Text);
cmd.Parameters.AddWithValue("#LName", tbLName.Text);
cmd.Parameters.AddWithValue("#PhoneNo", tbPhoneNo.Text);
cmd.Parameters.AddWithValue("#Address", tbAddress.Text);
cmd.Parameters.AddWithValue("#Email", tbEmail.Text);
cmd.Parameters.AddWithValue("#UserName", tbUserName.Text);
cmd.Parameters.AddWithValue("#Password", tbPassword.Text);
cmd.Parameters.AddWithValue("#Points", Points);
cmd.Parameters.AddWithValue("#Role", Role);
connection.Open();
cmd.ExecuteNonQuery();
}
finally
{
connection.Close();
//session
Session["UserName"] = tbUserName.Text;
Session["UserID"] = ("SELECT * FROM Users WHERE UserID = 'UserID'");
Session["Points"] = ("SELECT * FROM Users WHERE Points = 'Points'");
//pop out then redirect
ClientScript.RegisterStartupScript(this.GetType(), "Success", "<script type='text/javascript'>alert('Thank you or signing up with us!');window.location='Home.aspx';</script>'");
}
}
What should be the correct way to declare the connection first because I tried to put it before but I'm having problems with the cmd.
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
bool exists = false;
using (SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName"))
{
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}

You need to assign the connection to the command in your last example
So within your using statement add:
cmd.Connection = connection;
Additionally you don't need:
SqlCommand cmd;
as the command is created within the context of that using statement.
It's also considered good practice to wrap the Connection context within a using statement to ensure the actual connection get's disposed / closed correctly.

Try this,
using (SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"))
{
connection .Open();
SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName", connection );
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
bool exists = (int)cmd.ExecuteScalar() > 0;
}
You didn't specified connection to command. Secondly you have to open connection.
Update: Complete Code
try
{
string connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
bool exists = false;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection .Open();
SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName", connection );
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
if (exists)
{
lblUserName.Text = "This username has been used by another user.";
}
else
{
using(SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Users (UserID,FName, LName, PhoneNo, Address, Email, UserName, Password, Points, Role) VALUES (#UserID,#FName, #LName, #PhoneNo, #Address, #Email, #UserName, #Password, #Points, #Role)", Connection);
cmd.Parameters.AddWithValue("#UserID", UserID);
cmd.Parameters.AddWithValue("#FName", tbFName.Text);
cmd.Parameters.AddWithValue("#LName", tbLName.Text);
cmd.Parameters.AddWithValue("#PhoneNo", tbPhoneNo.Text);
cmd.Parameters.AddWithValue("#Address", tbAddress.Text);
cmd.Parameters.AddWithValue("#Email", tbEmail.Text);
cmd.Parameters.AddWithValue("#UserName", tbUserName.Text);
cmd.Parameters.AddWithValue("#Password", tbPassword.Text);
cmd.Parameters.AddWithValue("#Points", Points);
cmd.Parameters.AddWithValue("#Role", Role);
cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
//Do something
}
finally
{
//session
Session["UserName"] = tbUserName.Text;
Session["UserID"] = ("SELECT * FROM Users WHERE UserID = 'UserID'");
Session["Points"] = ("SELECT * FROM Users WHERE Points = 'Points'");
//pop out then redirect
ClientScript.RegisterStartupScript(this.GetType(), "Success", "<script type='text/javascript'>alert('Thank you or signing up with us!');window.location='Home.aspx';</script>'");
}

SQL command should have a overload which takes an initiated connection

Use SqlCommand constructor that takes connection as second argument. Next you have to open it before executing command and after that close it.
using (SqlCommand cmd = new SqlCommand("select * from [Users] where UserName = #UserName", connection))
{
cmd.Parameters.AddWithValue("UserName", tbUserName.Text);
connection.Open();
exists = (int)cmd.ExecuteScalar() > 0;
connection.Close();
}

Related

C# program does not connect to a database (freesqldatabase.com)

I'm using freesqldatabase.com to get a database for a college project, so having a remotely accessible database is needed. Unfortunately it does not connect to the database. It connects to their myphpadmin just fine but any other connection fails.
private void Submit_registration(object sender, RoutedEventArgs e)
{
SqlConnection sqlCon = new SqlConnection(#"Data Source= sql2.freesqldatabase.com; Initial Catalog=dbname; User ID=id;Password=no, Integrated Security= True;");
sqlCon.Open();
String query = "INSERT INTO tbluser (ID, username, password) VALUES (#ID, #username, #password)";
String query2 = "SELECT MAX(ID) FROM tbluser";
SqlCommand cmd2 = new SqlCommand(query2, sqlCon);
SqlCommand cmd = new SqlCommand(query, sqlCon);
int maxId = Convert.ToInt32(cmd2.ExecuteScalar());
int newmaxid = maxId + 1;
if (String.Equals(text_password.Password,text_password_confirm.Password))
{
cmd.Parameters.AddWithValue("#ID", newmaxid.ToString());
cmd.Parameters.AddWithValue("#username", textbox_username.Text);
cmd.Parameters.AddWithValue("#password", text_password.Password);
cmd.ExecuteNonQuery();
sqlCon.Close();
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
Close();
}
else
{
MessageBox messageBox = new MessageBox();
messageBox.Show();
sqlCon.Close();
}
}

An attempt to attach an auto-named database for file …LoginDB.mdf failed

string _connStr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\James JJ\Desktop\jj\Web App\Website\App_Data\LoginDB.mdf;Integrated Security=True";
string _query = "INSERT INTO [RegistrationTable] (Email, Password, HomeAddress, PostalCode, Gender) VALUES (#email, #password, #haddress, #postalcode, #gender)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#email", Emailtxt.Text);
comm.Parameters.AddWithValue("#password", Passwordtxt.Text);
comm.Parameters.AddWithValue("#homeaddress", hAddresstxt.Text);
comm.Parameters.AddWithValue("#postalcode", Postaltxt.Text);
comm.Parameters.AddWithValue("#gender", gender);
conn.Open();
comm.ExecuteNonQuery();
Response.Redirect("RegistrationSuccess.aspx");
}
}
I really tried all the solutions on the net but I still keep getting errors.

C# SQL Update CommandText and Parameters

I created a simple SQL database that has one table, tblCustomerInformation, and three columns :
FirstName,
LastName,
and Email.
I'm attempting to update it however when I run the code that I listed below the program does nothing.
It doesn't crash and give me errors it just does nothing.
I'm fairly certain that my UPDATE statement is correct. I'm not sure why this isn't working at this point.
using (SqlConnection Connection = new SqlConnection(#"Data Source=EWOODWARD-PC\SQL2012; Initial Catalog=CustomerGUI; Integrated Security=True"))
{
using (SqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = "UPDATE tblCustomerInformation SET LastName = #ln, Email = #em WHERE (FirstName = #fn)";
//cmd.Parameters.Add("#ln", SqlDbType.NVarChar);
//cmd.Parameters["#ln"].Value = txtLastName.Text;
//cmd.Parameters.Add("#em", SqlDbType.NVarChar);
//cmd.Parameters["#em"].Value = txtEmail.Text;
//cmd.Parameters.Add("#fn", SqlDbType.NVarChar);
//cmd.Parameters["#fn"].Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("#ln", txtLastName.Text);
cmd.Parameters.AddWithValue("#fn", txtFirstName.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
Connection.Open();
cmd.ExecuteNonQuery();
}
}
Use this. The arrangement of cmd.Parameters... code should not be jumbled. Base it on the arrangement in your query.
using (SqlConnection Connection = new SqlConnection(#"Data Source=EWOODWARD-PC\SQL2012; Initial Catalog=CustomerGUI; Integrated Security=True"))
{
using (SqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = "UPDATE tblCustomerInformation SET LastName = #ln, Email = #em WHERE FirstName = #fn";
cmd.Parameters.AddWithValue("#ln", txtLastName.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
cmd.Parameters.AddWithValue("#fn", txtFirstName.Text);
Connection.Open();
cmd.ExecuteNonQuery();
}
}
Have encountered this kind of error once.

Checking if user exists in MySQL database fails

Not sure why the following code gives me an exception. I'm trying to check if a username exists in a MySQL database, if not then I want to create a user. If I run either query by itself then it works ok but not together.
int valid = -1;
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
bool usernameExists = false;
string sql1 = String.Format("SELECT Username FROM Users WHERE Username = \"{0}\"", username);
MySqlCommand cmd1 = new MySqlCommand(sql1, cnn);
usernameExists = (int)cmd1.ExecuteScalar() > 0;
if (!usernameExists)
{
string sql = String.Format("INSERT INTO Users(Username, Password) VALUES(\"{0}\", \"{1}\")", username, password);
MySqlCommand cmd = new MySqlCommand(sql, cnn);
valid = cmd.ExecuteNonQuery();
}
}
return valid;
First, MySQL uses single quotes. This means your query would be:
string.format("SELECT Username FROM Users WHERE Username = '{0}' LIMIT 1", Username);
However, this is very vulnerable with SQL injection. Here's a code to use MySQL Parameters to prevent it.
int valid = -1;
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
bool usernameExists = false;
MySqlCommand cmd1 = new MySqlCommand("SELECT Username FROM Users WHERE Username = #username LIMIT 1", cnn);
cmd1.Parameters.AddWithValue("#username", username);
usernameExists = (int)cmd1.ExecuteScalar() > 0;
if (!usernameExists)
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO Users(Username, Password) VALUES(#username, #password)", cnn);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
valid = cmd.ExecuteNonQuery();
}
}
return valid;
Could you try this?
I got it working by changing the first query from:
MySqlCommand cmd1 = new MySqlCommand("SELECT Username FROM Users WHERE Username = #username LIMIT 1", cnn);
to
MySqlCommand cmd1 = new MySqlCommand("SELECT COUNT(UserID) FROM Users WHERE Username = #username", cnn);
int valid = int.Parse(cmd.ExecuteScalar().ToString());
Thanks for the help.

Syntax error near Source when trying to access a database C# asp.net

string databaseLocation = "|DataDirectory|\\Users.mdf";
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + databaseLocation + ";Integrated Security=True;User Instance=True";
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandText = String.Format("SELECT * FROM Users WHERE Username = {0}", username);
command.CommandType = CommandType.Text;
command.Connection = sqlConnection;
sqlConnection.Open();
int numberOfRows = command.ExecuteNonQuery();
sqlConnection.Close();
return numberOfRows;
This should check the Users.mdf database for the number of occorances of the username. but im getting a "syntax error near Source" runtime error when it hits the ExecuteNonQuery. I cant find anything wrong... Please help :)
Your formatted sql statement is not including delimiters for the username:
command.CommandText = String.Format("SELECT * FROM Users WHERE Username = {0}", username);
sets the command text to something like:
SELECT * FROM Users WHERE Username = foo
This is easily corrected, but it would be better to use a SqlParameter:
command.CommandText = "SELECT * FROM Users WHERE Username = #username");
command.Parameters.AddWithValue("#username", username);
Also, ExecuteNonQuery will return -1 for the number of rows affected, since the select doesn't affect rows. Instead do:
command.CommandText = "SELECT COUNT(*) FROM Users WHERE Username = #username");
command.Parameters.AddWithValue("#username", username);
...
int numberOfRows = (int)command.ExecuteScalar();
Your code should be:
string databaseLocation = "|DataDirectory|\\Users.mdf";
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + databaseLocation + ";Integrated Security=True;User Instance=True";
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT COUNT(*) FROM Users WHERE Username = #User";
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#User",username);
command.Connection = sqlConnection;
sqlConnection.Open();
int numberOfRows = command.ExecuteScalar();
sqlConnection.Close();
return numberOfRows;

Categories

Resources