Connection must be valid and open SQL - c#

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

Related

Connection is not closed properly ASP.NET C#

I have this button click event. Been trying to replace the con.Close() in different lines of code, tried for hours but couldn't fix. Maybe a second pair of eyes can help?
Error: System.InvalidOperationException: 'The connection was not closed. The connection's current state is open.'
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
con.Open();
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
cmd.Parameters.AddWithValue("#CATEGORY", DropDownList1.SelectedItem.Value);
lblResult.Text = "You have selected this category. Please select a new category";
con.Close();
}
else
{
SqlCommand cmd1 = new SqlCommand("UPDATE SET CATEGORY CCID#CCID (CATEGORY, C_USERNAME, CCID) VALUES (#CATEGORY, #C_USERNAME, #CCID)", con);
cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value);
cmd1.Parameters.AddWithValue("C_USERNAME", Session["id"]);
cmd1.Parameters.AddWithValue("CCID", Label1.Text);
con.Open();
int i = cmd1.ExecuteNonQuery();
con.Close();
if (i != 0)
{
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
}
else
{
Label2.Text = "Something went wrong with selection";
Label2.ForeColor = System.Drawing.Color.Red;
}
}
}
Try this (open connection only once and close only once):
protected void Button1_Click(object sender, EventArgs e) {
using(SqlConnection con = new SqlConnection()) {
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
bool hasRows = reader.HasRows;
reader.Close();
if (hasRows) {
// This line makes no sense after the execution of the query.
//cmd.Parameters.AddWithValue("#CATEGORY", DropDownList1.SelectedItem.Value);
lblResult.Text = "You have selected this category. Please select a new category";
} else {
SqlCommand cmd1 = new SqlCommand("UPDATE SET CATEGORY CCID#CCID (CATEGORY, C_USERNAME, CCID) VALUES (#CATEGORY, #C_USERNAME, #CCID)", con);
cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value);
cmd1.Parameters.AddWithValue("C_USERNAME", Session["id"]);
cmd1.Parameters.AddWithValue("CCID", Label1.Text);
int i = cmd1.ExecuteNonQuery();
if (i != 0) {
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
} else {
Label2.Text = "Something went wrong with selection";
Label2.ForeColor = System.Drawing.Color.Red;
}
}
con.Close();
}
}
Now let's discuss this line
string query = "SELECT CATEGORY FROM CATEGORY WHERE C_UserName = '" + Session["id"] + "' AND CATEGORY = '" + DropDownList1.SelectedItem.Value + "' ";
This let's attacker manipulate your input with sql injection. To solve this, use the same cmd1.Parameters.AddWithValue("CATEGORY", DropDownList1.SelectedItem.Value); that you are using in the second query. The Session["id"] is somewhat safer as it is not provided by the user but better safe than sorry as the parameters sanitize the input and protect you from sql injection.

Check if same username exists in sql server management..... if so dont add the username

It is showing me 2 errors.. please help .....required for my project work
The error showing in both cases is as follows:-
Error 1 'System.Data.SqlClient.SqlDataAdapter' does not contain a
definition for 'loginregistration' and no extension method
'loginregistration' accepting a first argument of type
'System.Data.SqlClient.SqlDataAdapter' could be found (are you missing
a using directive or an assembly reference?)
private void btnSave_Click(object sender, EventArgs e)
{
{
if (txtUsername.Text == "" || txtEmail.Text == "")
{
MessageBox.Show("Please enter all Details");
}
else
{
SqlCommand cmd = new SqlCommand("select * from loginregistration WHERE username='" + txtUsername.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
int i = da.loginregistration[0].Rows.Count;//.........(ERROR HERE)
if (i > 0)
{
MessageBox.Show("Username Already Exists");
da.Clear();//............(ERROR HERE)
}
else
{
try
{
SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "insert into loginregistration(username,FirstName,LastName,Email,Address,Contact_No) VALUES('" + txtUsername.Text + "','" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + "','" + txtAddress.Text + "','" + txtContact.Text + "')";
cmd1.ExecuteNonQuery();
con.Close();
disp_data();
MessageBox.Show("Inserted Successfully");
txtUsername.Text = txtFirstName.Text = txtLastName.Text = txtEmail.Text = txtContact.Text = txtAddress.Text = "";
}
catch (Exception ex)
{
MessageBox.Show("ex.Message");
}
}
}
}
}
Let's extract a method for checking user's existence. We don't need to load all the data into a DataTable with a help of SqlDataAdapter; one query will be enough:
private bool UserExists(string userName) {
if (null == userName)
return false;
using (SqlConnection conn = new SqlConnection("Connection_String_Here")) {
conn.Open();
// Keep query readable
// Make query parametrized
string sql =
#"select 1
from LoginRegistration
where UserName = #prmUserName";
// Do not share the single connection, but create a new one
using (SqlCommand q = new SqlCommand(sql, conn)) {
q.Parameters.Add("#prmUserName", SqlDbType.VarChar).Value = userName;
// If we can read at least one record
using (var reader = q.ExecuteReader()) {
// we can be sure the user exists
return reader.Read();
}
}
}
}
Now, let's use our method:
if (string.IsNullOrEmpty(txtUsername.Text) || string.IsNullOrEmpty(txtEmail.Text))
MessageBox.Show("Please enter all Details");
else {
if (UserExists(txtUsername.Text))
MessageBox.Show("Username Already Exists");
else {
...
}
}
try to use dataset
DataSet loginregistration = new DataSet();
da.Fill(loginregistration ,"loginregistration ");
To fix your existing code:
int i = da.loginregistration[0].Rows.Count;
should be
int i = ds.Tables[0].Rows.Count;
That said you should pay attention to the answer Dmitry gave and parameterise your SQL. Your current method is wide open to SQL Injection.

Retrieving BLOB from database and save it locally

I am trying to retrieve a blob that i have stored in the database.
I would then like to store it locally on my pc. ive got this far, but i`m stuck for some time now. can anybody helpt me realise this?
private void button1_Click(object sender, EventArgs e)
{
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
//
MySqlCommand SelectCommand = new MySqlCommand("select template from csharp.members where username='" +
this.user_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)
{
byte[] tmp = (byte[])(myReader["template"]); // need to save this locally
}
}
Please try this.
File.WriteAllBytes("filename", tmp); // Requires System.IO

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