I'm trying to check if the username is already in use in C# database and it's giving me this error
SqlConnection cn = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\admin\Desktop\241 Project sem 1 2020-2021\Online Banking - ITIS 241 project group 9\UobBankDatabase.mdf; Integrated Security = True; Connect Timeout = 30");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from LoginTable where user_name='" + textBox1.Text + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
MessageBox.Show("Username Already exist please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dr.Close();
}
and yes I'm a newbie
Use this:
SqlCommand cmd = new SqlCommand("Select count(*) from LoginTable where user_name='" + textBox1.Text + "'", cn);
Then:
var dr = cmd.ExecuteScalar();
if (dr != null)
{
//Exists
}
else
{
//Unique username
}
Google it please:
Since the error is SqlException: Invalid object name 'Movie' , that
means the table named 'Movie' has not created or the Database you are
referring has not created. To see if the Database or table 'Movie' has
created, open SQL Server Object Explorer and check the Database name
is the same as in appsettings. json
And Please tell us at what line do you get that?
Is that this line =>if (dr.Read())
Let's extract method for the check:
private static bool NameAvailable(string name) {
//DONE: wrap IDisposable into using
using (SqlConnection cn = new SqlConnection("Connection String Here")) {
cn.Open();
//DONE: keep Sql readable
//DONE: make Sql parametrize
//DONE: select 1 - we don't want entire record but a fact that record exists
string sql =
#"select 1
form LoginTable
where user_name = #prm_user_name";
using (var cmd = new SqlCommand(sql, cn)) {
cmd.Parameters.Add("#prm_user_name", SqlDbType.VarChar).Value = name;
using (var dr = cmd.ExecuteReader()) {
return !dr.Read(); // Not available if we can read at least one record
}
}
}
}
Then you can put
if (!NameAvailable(textBox1)) {
// Let's be nice and put keyboard focus on the wrong input
if (textBox1.CanFocus)
textBox1.Focus();
MessageBox.Show("Username Already exist please try another ",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
some changes only.it is better to get what is the error than a temporary solution so print your query first and run it in the sqlserver . also add initial catalog instead of attacjing mdf files its way better in my opinion.
<connectionStrings>
<add name="stringname" connectionString="Data Source=mssql;Initial Catalog=databasename; Persist Security Info=True;User ID=sa;Password=*****;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
using a connection string instead also
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["stringname"].ConnectionString);
cn.Open();
string query = "select * from LoginTable where user_name='" + textBox1.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dr = cmd.ExecuteReader();
//print query if error and comment the execute reader section when printing the query to know the error Respone.Write(query);
if (!dr.HasRows)
{
// ur code to insert InsertItemPosition values
}
else
{
//show username exist
}
dr.Close();
Try this:
string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(UserName) as UserCount FROM LoginTable WHERE user_name = #user_name", con))
{
con.Open();
cmd.Parameters.AddWithValue("#user_name", TextBox1.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if(Convert.ToInt32(dr["UserCount"].ToString()) >= 1)
{
// Exists
}
else
{
// Doesn't Exist
}
}
}
con.Close();
}
}
Related
string constr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\jettp\Downloads\MockTest\MockTest\Database1.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, Weight FROM MyWeight where Name ='" + txt_Name.Text + "'"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (txt_Name.Text != null)
{
sdr.Read();
MessageBox.Show("Username is found");
txt_Name.Text = sdr["Name"].ToString();
txt_Weight.Text = sdr["Weight"].ToString();
con.Close();
}
else
{
lbl_WarningMsg.Text = "Name not found";
con.Close();
}
}
}
}
I tried using this command to search for the username which is in not found database, but database message kept saying that the name is found in the database. This is the error I get:
System.InvalidOperationException: 'Invalid attempt to read when no data is present.'
You are getting that Username is found because your if condition is always true. Change your if condition to this :
if (sdr.HasRows)
{
//your code
}
I have a simple login website, which is my first website project in Visual Studio 2015. I have successfully created a SQL database which contains user information like Username, Password, Email and Country, and I have also successfully created a user registration page where a new user can input there details and these details will be added to the database. This all works fine.
but I have hit a roadblock while attempting to validate the Username and Password against the stored values in the row containing the User data in the SQLdatabase to give the user access to the member only pages.
Heres my code snippet for when the user click the login button.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString);
con.Open();
string checkUser = "SELECT * FROM Members where Username= '" + TextBoxSignUser.Text + "' and Password= '" + TextBoxSignPass.Text + "'";
SqlCommand cmd = new SqlCommand(checkUser, con);
cmd.ExecuteNonQuery();
con.Close();
I know what I need to do is probably something like this pseudocode below, but I am unsure how to go about validating this information against stored values in the database.
if ("Username" and "Password" == the value of Username and Password TextBox.Text)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
else
{
Response.Write("Details incorrect, Please try again")
}
Fill the data-table using data adapter one you get the data into a data-table you can get the return values of the query and match the parameters
DataTable Dt = new Datatable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.rows.count > 0 )
{
//MATCH FOUND
}
You can use like..
string query= "SELECT * FROM Members where Username= 'usr' and Password= 'pwd'";
SqlCommand cmd = new SqlCommand(query, con);
MySqlDataAdapter objda = new MySqlDataAdapter(cmd);
DataSet objDs = new DataSet();
objda.Fill(objDs);
if(objDs.Tables[0].Rows.Count>0)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
You could do as following without using Datasets,
var con = new SqlConnection("your connection string goes here");
SqlCommand cmd = new SqlCommand("SELECT * FROM Members where Username= 'usr' and Password= 'pwd'", con);
bool result = false;
cmd.Connection.Open();
using (cmd.Connection)
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
result = true;
}
if (result == true)
// Login successful
else
// Login failed
string query = string.Format("SELECT TOP 1 * FROM [Table] WHERE Username = '{0}' and Password = '{1}'", txtUsername.Text, txtPassword.Text);
command = new OleDbCommand(query, con);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
//successfully login
}
else
//error message
I think first of all it is better to use ADO.NET libraries for some reasons like best performance and high security. Here is my suggestion. hope to be useful for you:
using System.Data.SqlClient;
...
string conStr = ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString;
string sql = "SELECT * FROM Members where Username = #user and Password = #pass";
SqlParameter pUser = new SqlParameter("#user", TextBoxSignUser.Text);
SqlParameter pPass = new SqlParameter("#pass", TextBoxSignPass.Text);
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add(pUser);
cmd.Parameters.Add(pPass);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
// Successfully signed in
// Also you can access your fields' value using:
// 1. its index (e.x. reader[0])
// 2. or its name: (e.x. reader["Username"])
}
else
{
// Login failed
}
}
}
}
try
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= C:\Users\jay.desai\Documents\Visual Studio 2008\Projects\Jahoo Sign in form!\Jahoo Sign in form!\Registration_form.mdb");
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from Login where Username='"+txtlognUsrnm.Text+"' and Password='"+txtlognpswrd+"'", con);
OleDbDataReader dr = cmd.ExecuteReader();
if(dr.Read() == true)
{
MessageBox.Show("Login Successful");
}
else
{
MessageBox.Show("Invalid Credentials, Please Re-Enter");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I have created one login form and one table in microsoft access which contains username and password fields.when i click on login button it always shows else message though the username and password is same as in table.
The word PASSWORD is a reserved keyword in access-jet. You need to encapsulate it in square brackets.
OleDbCommand cmd = new OleDbCommand("select * from Login where Username=" +
"? and [Password]=?", con);
Also do not use string concatenation to build sql commands but a parameterized query
There are other problems in your code above.
First try to use the using statement to be sure that the connection and other disposable objects are correctly closed and disposed.
Second, if you need only to check the login credentials, then there is no need to get back the Whole record and you could use the ExecuteScalar method avoiding the OleDbDataReader object
string constring = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= C:\Users\jay.desai\Documents\Visual Studio 2008\Projects\Jahoo Sign in form!\Jahoo Sign in form!\Registration_form.mdb";
string cmdText = "select Count(*) from Login where Username=? and [Password]=?"
using(OleDbConnection con = new OleDbConnection(constring))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.AddWithValue("#p1", txtlognUsrnm.Text);
cmd.Parameters.AddWithValue("#p2", txtlognpswrd.Text); // <- is this a variable or a textbox?
int result = (int)cmd.ExecuteScalar()
if(result > 0)
MessageBox.Show("Login Successful");
else
MessageBox.Show("Invalid Credentials, Please Re-Enter");
}
I've seen this question asked a couple times but I couldn't find a good answer. I've been stuck for hours on this.
Basically I have usernames saved in a database and when a new user registers I want to check if his username is available - and if it is available add him to the database. And they register through a textbox called FName. The table is called Users.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT FName FROM Users WHERE FName = ????? usernames????? ", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["text"].ToString());
}
How can I fix this code?
"SELECT FName FROM Users WHERE FName = #paramUsername"
and then you insert the parameter into the cmd like so:
cmd.Parameters.Add("paramUsername", System.Data.SqlDbType.VarChar);
cmd.Parameters["paramUsername"].Value = "Theusernameyouarelookingfor";
Check this out:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string validationQuery = "SELECT * FROM Users WHERE FName = #name";
SqlCommand validationCommand = new SqlCommand(validationQuery, connection);
validationCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
SqlDataReader validationReader = validationCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (!validationReader.Read())
{
string insertQuery = "INSERT INTO Users (FName) VALUES (#name)";
SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
insertCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
insertCommand.ExecuteNonQuery();
insertCommand.Dispose();
connection.Close();
}
else
{
//Uh oh, username already taken
}
validationReader.Close();
validationCommand.Dispose();
Things to note:
Use parameters, avoid concatenating strings because it's a security vulnerability
Always Close and Dispose your ADO objects
private void d_Load(object sender, EventArgs e)
{
string connstring = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\it155.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection conn = new SqlConnection(connstring);
try
{
conn.Open();
string snumber = txtSnumber.Text;
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber ='" + txtSnumber.Text + "'", conn);
}
catch (Exception)
{
}
}
given the start of the code which is written above, what i plan to do is to be able to log in using id number datatype varchar(11) in the sql database which was to be entered in the txtSnumber but aside that i cant figure out how to check whether the id number entered is correct or not and if it is correct, the information corresponding to that id number enetered is supposed to show in the their corresponding textboxes. please help me, thanks
Your sql statement is prone to SQL Injection. Is terrible practice to concatenate SQL like this. Instead do something like this:
string snumber = txtSnumber.Text;
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber =#User", conn);
get.Parameters.AddWithValue("#User",snumber);
Now, in order to check whether the record was found or not, you do this:
using(IDataReader reader = get.ExecuteReader())
{
if (reader.HasRows)
{
//information correct. Do something
}
}
You can check it by using a DataReader()
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber ='" + txtSnumber.Text + "'", conn);
SqlDataReader myReader = get.ExecuteReader();
if (myReader.HasRows)
{
MessageBox.Show("ID is valid");
while (myReader.Read())
//Do something here
}
else
MessageBox.Show("Given ID is Invalid.");
EDIT:
While calling ExecuteReader() method you put the following argument inside it, so that when ever you close the connection the datareader also automatically closes.
SqlDataReader myReader = get.ExecuteReader(CommandBehavior.CloseConnection);