fatal error encountered during command execution c# mysql - c#

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

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 :)

Update query not working in C#

protected void btn_redeem_Click(object sender, EventArgs e)
{
int lol = int.Parse(lbl_TotalPrice.Text,System.Globalization.NumberStyles.Currency);
double nprice = lol * 0.05;
int newpoints=0 ;
if (int.Parse(Session["points"].ToString()) >= 1000)
{
double redeem = lol - nprice;
lbl_TotalPrice.Text = redeem.ToString("C");
newpoints = int.Parse(Session["points"].ToString()) - 1000;
}
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString);
conn.Open();
string queryStr = "UPDATE Users SET Points ='" + newpoints + "'WHERE UserName=" + Session["New"].ToString();
SqlCommand com = new SqlCommand(queryStr, conn);
conn.Close();
}
Add .ExecuteNonQuery to execute the query, and add try-catch-block to catch any exception:
try
{
...
SqlCommand com = new SqlCommand(queryStr, conn);
com.ExecuteNonQuery();
conn.Close();
...
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

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

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.

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);
}

Different form opens when you login as admin c# mysql

So i've made a login form in c# working with MySql and i want to make it so when administrator login a different form pops up i've made on the mysql in the users database a column named permissions so if a user will have permission Admin i want a different form to open for him and not the same as for normal users but i don't really know how to do that
the code:
private void btn_Prijava_Click(object sender, EventArgs e)
{
try
{
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(" select * from login.users where upIme='" + this.tB_upIme.Text + "' AND geslo='" + this.tB_geslo.Text + "' ;", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Uspešno ste se prijavili!");
this.Hide();
Form3 f3 = new Form3();
f3.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Dvojno uporabniško ime in geslo!");
this.Hide();
}
else
MessageBox.Show("Uporabniško ime ali geslo ni pravilno!");
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
if you have permissions column and have value Admin for admin users you can try thebelow code.
bool IsAdminUser=false;
while (myReader.Read())
{
count = count + 1;
IsAdminUser = myReader["permissions"].ToString().Equals("Admin");
}
if (count == 1 && IsAdminUser==true)
{
MessageBox.Show("User is Admin!");
this.Hide();
AdminForm adminForm = new AdminForm ();
adminForm.ShowDialog();
}
else if (count == 1)
{
MessageBox.Show("Uspešno ste se prijavili!");
this.Hide();
Form3 f3 = new Form3();
f3.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Dvojno uporabniško ime in geslo!");
this.Hide();
}
private void cmdEnter_Click(object sender, EventArgs e)
{
try
{
string myConnection = "datasource=localhost;port=3306;username=root;password=1234";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(" select * from boardinghousedb.employee_table where username='" + this.txtUsername.Text + "' AND password='" + this.txtPassword.Text + "' ;", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
bool IsAdminUser = false;
while (myReader.Read())
{
count = count + 1;
IsAdminUser = myReader["username"].ToString().Equals("admin");
}
if (count == 1 && IsAdminUser == true)
{
MessageBox.Show("User is Admin!");
this.Hide();
AdminForm adminForm = new AdminForm();
adminForm.ShowDialog();
}
else if (count == 1)
{
this.Hide();
Menu f3 = new Menu();
f3.ShowDialog();
}
else if (count > 1)
{
MessageBox.Show("Duplicate Username and Password . . . Access Denied", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Username and Password is Not Correct . . . Please try again", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
myConn.Close();
}
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Categories