Invalid attempt to Read when reader is closed. C# Mysql - c#

This script is on the register page of my visual basic application.
The script saves the data in the database with no errors only when i close the application it gives me the error invalid attempt to read when reader is closed. This only happens on this page
if (PasswordRegister.Text == RepeatPasswordRegister.Text)
{
if (PasswordRegister.Text == "")
{
MessageBox.Show("Enter a vailed password");
}
else if (UsernameRegister.Text == "")
{
MessageBox.Show("Enter a vailed Username");
}
else {
string myConnection = "datasource=127.0.0.1;port=3306;username=root;password=Root;";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand Login = new MySqlCommand("select * from database.users where Username='" + this.UsernameRegister.Text + "' ;", myConn);
MySqlDataReader RegisterReader;
myConn.Open();
RegisterReader = Login.ExecuteReader();
int count = 0;
while (RegisterReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username is taken");
}
else if (count > 1)
{
MessageBox.Show("ERROR Contact support");
}
else {
string constring = "datasource=127.0.0.1;port=3306;username=root;password=Root;";
string Query = "insert into database.users (Username, Password) values ('" + this.UsernameRegister.Text + "','" + this.PasswordRegister.Text + "') ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Register Succes");
conDataBase.Close();
conDataBase.Dispose();
this.Hide();
Form1 home = new Form1();
home.ShowDialog();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
myConn.Close();
}
}
else {
MessageBox.Show("Check password");
};

If you look at your code carefully, you'll note that you've closed the connection before you try and read from the reader:
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
conDataBase.Close(); *** Connection closed here
conDataBase.Dispose(); *** And disposed disposed, for good measure
...
while (myReader.Read()) *** Now you are trying to Read!
{
}
What you need to do is keep the connection Open until you've finished reading, e.g.
using (var myConn = new MySqlConnection(myConnection))
using (var Login = new MySqlCommand("select * from database.users where Username= #myUserName",
myConn);
{
cmdDataBase.AddWithValue(new MySqlParameter("#myUserName", this.UsernameRegister.Text));
conDataBase.Open();
using (var myReader = cmdDataBase.ExecuteReader())
{
while (myReader.Read())
{
// Do something with myReader[] fields here
}
} // Reader disposed
} // Command Disposed, Connection Closed + Disposed
I would also prefer the using syntax to manage disposables such as Connections, Commands, and Readers, and at the same time, parameterize your queries and commands - this has security, and possibly also performance benefit.

Related

Connection must be valid and open SQL

There was a problem. I checked the connection to the database - everything works.
But when I try to check the lines in the database, then the error pops up:
System.InvalidOperationException: "Connection must be valid and open." c#
How can i fix this?
private void button1_Click(object sender, EventArgs e)
{
try
{
MySqlConnection conn = GetDBConnection();
conn.Open();
MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM 'rcc_base' WHERE login='" + this.textBox1.Text + "', pass='" + this.textBox2.Text + "' ;");
MySqlDataReader myReader;
MessageBox.Show("Connection...");
myReader = selectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("All nice");
}
else
{
MessageBox.Show("Login failed");
}
conn.Close();
}
catch (Exception)
{
MessageBox.Show("Error");
}
}
In your MySqlCommand you are not using your MySqlConnection :( .So change it as follows
MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM rcc_base WHERE 'login' ='" + this.textBox1.Text + "' AND 'pass' ='" + this.textBox2.Text + "' ;",conn);
Also , create a new instance of the MySqlConnection like :
MySqlConnection conn = new MySqlConnection;
conn = GetDBConnection();
And a few suggestions:Your code is not good.Don't give direct values to columns in the SqlCommand rahter pass parameters like #abc , this will also prevent sql-injections.Sample :
MySqlCommand selectCommand = new MySqlCommand("SELECT COUNT(*) FROM rcc_base WHERE login=#username AND pass=#password;",conn);
selectCommand.Parameters.Add("#username",MySqlDbType.VarChar).Value = textBox1.Text;
selectCommand.Parameters.Add("#password",MySqlDbType.VarChar).Value = textBox2.Text;
///Now to check if data exists in the database or not
int count = Convert.ToInt32(selectCommand.ExecuteScalar());
if(count > 0)
{
///data exists-login successful
}
else
{
///data doesn't exists , login failed
}
Also you should open the connection on form load so that you can access the database throughout the class/form.It is a better way to do it :)

C# Login System Expiration Date

This is the code i'm using for c# mysql login system
try
{
MySqlConnection connection = new MySqlConnection("Server=localhost; database=member; UID=root; Pwd=");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM member.member WHERE username='" + this.metroTextBox1.Text + "' AND password='" + this.metroTextBox2.Text + "' ;", connection);
MySqlDataReader myReader;
connection.Open();
myReader = cmd.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
Form2 frm = new Form2();
frm.username = metroTextBox1.Text;
frm.Show();
this.Visible = false;
}
else
{
MetroMessageBox.Show(this, "Incorrect login credentials. Failed to login!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
And this is my database
http://i.imgur.com/K831atR.png
Basically i want to block login if expirationdate passed. But i've no clue what to do.
Try this:
try
{
MySqlConnection connection = new MySqlConnection("Server=localhost; database=member; UID=root; Pwd=");
connection.Open();
// Using parameters to prevent SQL Injections
MySqlCommand cmd =
new MySqlCommand("SELECT * FROM member.member WHERE username=#username AND password=#password ;",
connection);
cmd.Parameters.AddWithValue("#username", this.metroTextBox1.Text);
cmd.Parameters.AddWithValue("#password", this.metroTextBox2.Text);
var myReader = cmd.ExecuteReader();
if (myReader.HasRows)
{
//Record found
myReader.Read();
// Assuming there's always a valid date in your table otherwise
// an exception will be thrown while trying to convert to a DateTime object
var expiryDate = myReader.GetDateTime("expirationdate");
// Use this to show the remaining days on your label
int remainingDays = (int) (DateTime.Now - expiryDate).TotalDays;
string labelCaption = String.Format("You have {0} day(s) left.", remainingDays);
if (DateTime.Now > expiryDate)
{
//Login Expired
}
else
{
//Login is still valid
Form2 frm = new Form2();
frm.username = metroTextBox1.Text;
frm.Show();
this.Visible = false;
}
}
else
{
//No record found
MetroMessageBox.Show(this, "Incorrect login credentials. Failed to login!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception)
{
// Do your exception handling
}

C# and Oracle, login Form: Operation is not valid due to the current state of the object

private void bLogIn(object sender, EventArgs e)
{
string logging = "select * from CLIENT where LOGIN='" + this.t_Login.Text + "' and PASSWORD='" + this.t_Password.Text + "' ;";
OracleConnection conn = new OracleConnection("Data Source=XXX/orcl;User Id=XXX;Password=XXX;");
OracleCommand cmd = new OracleCommand();
cmd.CommandText = logging;
cmd.Connection = conn;
try
{
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
int count = 0;
OracleDataReader reader = cmd.ExecuteReader(); // At this line there is the error: Operation is not valid due to the current state of the object
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Welcome");
}
else
{
MessageBox.Show("Wrong Password");
}
conn.Dispose();
}
This is code that was working for MySQL, but after conversion to Oracle it's not working. What am I doing wrong? Where's the difference. It should be so easy as in MySQL, right?
Why "OracleDataReader reader = cmd.ExecuteReader();" causes error: "Operation is not valid due to the current state of the object" ???
You are not assingning the connection to cmd.. try code below
OracleCommand cmd = new OracleCommand();
cmd.connection = conn;
cmd.CommandText = logging;
int count = 0;
OracleDataReader reader = cmd.ExecuteReader();

create a login page in vb.net by c# & mysql but it shows error message connection must be valid and open

private void admin_submit_button_Click(object sender, EventArgs e)
{
try
{
string myConnection = "datasource= localhost;port=3306;username=root;password=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand("select * from mws.login_info where login_id='" + this.admin_id_textbox + "'and login_password1='" + this.admin_password_textbox1 + "' and login_password2='" + this.admin_password_textbox2 + "'");
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("username and password is correct");
}
else
MessageBox.Show("username and password not correct");
myConn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
You have not associated the command with the connection. You code lacks of the following line
SelectCommand.Connection = myConn ;
Said that, imagine that I write in your admin_id_textbox the following text
' OR login_id like '%' --
what happen to your checks for the correct login?
It is called Sql Injection and it is a very dangerous situation for every kind of database access.
Use always a parameterized query to build sql commands, in particular when part of your command is built using user input text
private void admin_submit_button_Click(object sender, EventArgs e)
{
try
{
string cmdText = #"select * from mws.login_info
where login_id=#id and login_password1=#pwd
and login_password2=#pwd2";
string myConnection = "datasource= localhost;port=3306;username=root;password=root";
using(MySqlConnection myConn = new MySqlConnection(myConnection))
using(MySqlCommand SelectCommand = new MySqlCommand(cmdText, myConnection))
{
myConn.Open();
SelectCommand.Parameters.AddWithValue("#id", this.admin_id_textbox);
SelectCommand.Parameters.AddWithValue("#pwd",this.admin_password_textbox1);
SelectCommand.Parameters.AddWithValue("#pwd2",this.admin_password_textbox2);
using(MySqlDataReader myReader = SelectCommand.ExecuteReader())
{
if(myReader.HasRows)
MessageBox.Show("username and password is correct");
else
MessageBox.Show("username and password not correct");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

fatal error encountered during command execution c# mysql

private void button1_Click_1(object sender, EventArgs e)
{
try
{
string myConnection = " datasource=**.**.**.**;port=3306;username=****;password=****;";
MySqlConnection myconn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(" select * from forma.user where username='" + this.username_txt.Text + "' and password= '" + this.password_txt.Text + "' ; ", myconn);
MySqlDataReader myreader;
myconn.Open();
myreader = SelectCommand.ExecuteReader();
int count = 0;
while (myreader.Read())
{
count = count + 1;
}
if (count == 1)
{
// MessageBox.Show("Prijava uspešna");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Podobojeno uporabniško ime");
}
else
{
MessageBox.Show("uporabniško ime ali geslo ni pravilno.");
myconn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a problem connecting to remote server, it gives me error (title). Can you please tell me what I did wrong and how can I fix it? Thanks.
give the connection string as below
string myConnection = "Server=**.**.**.**;Port=3306;Database=***;Uid=***;Pwd=***;"
Use SQL parameters, your application is widely open for sql injection attacks

Categories