I am getting error:
Connection must be valid and Open c# Winform.
Here is my code, can anyone please help what is wrong in the below code?
public void NameSearch()
{
listBox1.Visible = true;
try
{
String constring = "datasource=localhost;port=3306;Initial Catalog = 'svms'; username = svms; password =svms2016CPU";
string query = "select * from studentinformation where StudLname='" + metroTextBox1.Text + "'";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
MySqlDataReader myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string Lname = myReader.GetString(myReader.GetOrdinal("StudLname"));
string Fname = myReader.GetString(myReader.GetOrdinal("StudFname"));
string Mname = myReader.GetString(myReader.GetOrdinal("StudMname"));
string nameResult = Lname + ", " + Fname + " " + Mname;
listBox1.Items.Add(nameResult);
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You haven't open connection before use it, Open connection
conDataBase.Open();
Open the conn before read:
conDataBase.Open();
Like:
String constring = "datasource=localhost;port=3306;Initial Catalog = 'svms'; username = svms; password =svms2016CPU";
string query = "select * from studentinformation where StudLname='" + metroTextBox1.Text + "'";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
//
conDataBase.Open();
//
MySqlDataReader myReader = cmdDataBase.ExecuteReader();
Related
I am trying to have c# look to see if the database table equals what i am asking it to equal to open a specific form here is one way i am try doing it
void getsformat()
{
string constring = #"server=host;userid=user;password=pass";
string Query = "select colum from table where callsign= '" + listBox1.SelectedItem + "'";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sfName = myReader.GetString("sformat");
}
if (sfName == "stworld")
{
sendtext = textBox1.Text;
Form3 f3 = new Form3();
f3.Location = new Point(this.Top);
f3.ShowDialog();
}
else if (sfName == "seperate")
{
sendtext = textBox1.Text;
Form3 f4 = new Form3();
f4.Location = new Point(this.Top);
f4.ShowDialog();
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and the othere way with the "while myreader "end quote after the "if" statement
void getsformat()
{
string constring = #"server=host;userid=user;password=pass";
string Query = "select colum from table where callsign= '" + listBox1.SelectedItem + "'";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sfName = myReader.GetString("sformat");
if (sfName == "stworld")
{
sendtext = textBox1.Text;
Form3 f3 = new Form3();
f3.Location = new Point(this.Top);
f3.ShowDialog();
}
else if (sfName == "seperate")
{
sendtext = textBox1.Text;
Form3 f4 = new Form3();
f4.Location = new Point(this.Top);
f4.ShowDialog();
}
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i cannot get either of them to work . Any help would be apreciated
thank you in advanced
It doesn't look like you have the connection string setup properly.
This:
string constring = #"server=host;userid=user;password=pass";
Should have the relevant info
string constring = #"server=localhost\SQL2008;userid=myusername;password=mypass";
In your select statement change it to
listbox1.selecteditem.tostring();
I've created a database using mysql, on my form1 there are two textboxes username and password and a login button. My program retrieves information from database and if the data s matches it logs in else an messagebox should pop up telling that username of password is wrong ( which it doesn't show)
before posting the code:
I've declared: the following
public int logid;
public int loginid(strign name) // to set logid the id of the user
public void loginfun(); // checks the data and logs in if id and password matches, else should give an error message.
and my code is as follows:
public int loginid(string name)
{
string conString = "Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string getid = "SELECT username,id from ozturk.admin WHERE username='" + name + "'";
MySqlCommand cmd = new MySqlCommand(getid, mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
if (myReader["username"].ToString() == name)
{
return Convert.ToInt32(myReader["id"].ToString());
}
}
return 0;
}
public void loginfun()
{
string conString ="Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string selectCommand = "SELECT * FROM ozturk.admin";
MySqlCommand cmd = new MySqlCommand(selectCommand,mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// set logid to userid
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
}
catch (Exception)
{
MessageBox.Show("Username or Password is incorrect");
throw;
}
}
}
The problem is: My program logs in and opens the other form if the username and the password is correct however it doesn't do anything if the username or password is wrong, What am I missing here? any help is appreciated
Thanks
I've solved the problem, here is what I've done: I've changed my login function from void to bool: here is the latest code:
public bool loginfun()
{
string conString ="Server=localhost;Database=ozturk;Uid=_____;pwd=_____";
MySqlConnection mcon = new MySqlConnection(conString);
string selectCommand = "SELECT * FROM ozturk.admin";
MySqlCommand cmd = new MySqlCommand(selectCommand,mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// giriş yapan kişinin id si
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
return true;
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
throw;
}
}
return false;
}
and inside the login button the code is as follows:
if (loginfun() == true)
{
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
else
{
MessageBox.Show("Username or Password is incorrect");
}
Thank you everyone for the tips
This is your code:
bool flag = false;
while (myReader.Read())
{
try
{
if (myReader["username"].ToString() == txtuserid.Text && myReader["password"].ToString() == txtpassword.Text)
{
// set the flag to true, is credentials match and break from the loop
flag = true;
break;
// set logid to userid
logid = loginid(myReader["username"].ToString());
string updateCommand = "UPDATE ozturk.admin SET status = 'on' WHERE id='" + logid + "' ";
MySqlConnection newcon = new MySqlConnection(conString);
MySqlCommand cmd2 = new MySqlCommand(updateCommand, newcon);
MySqlDataReader myReader2;
newcon.Open();
myReader2 = cmd2.ExecuteReader();
Anasayfa anasayf = new Anasayfa();
anasayf.Show();
this.Hide();
}
}
catch (Exception)
{
MessageBox.Show("Username or Password is incorrect");
throw;
}
}
if(!flag)
{
MessageBox.Show("Username or Password is incorrect");
}
I'm building an application with C# code.
This is a simple code for inserting values unto the database. I have successfully inserted the values but when I checked on the time column where I have used the datetimepicker, it would only show 0000-00-00 00:00:00. So my problem is, How can you insert time and date only into the database?
private void button1_Click(object sender, EventArgs e)
{
string constring = "Database=fillupform;Data Source=localhost;User Id=root;Password=''";
timeanddate.Format = DateTimePickerFormat.Custom;
timeanddate.CustomFormat = "MM dd yyyy hh mm ss"; timeanddate.Value.ToShortDateString();
string Query = "Insert into fillupform.fillupform (filename,instructor,time,score) values('" + this.filename.Text + "','" + this.instructor.Text + "','" + this.timeanddate.Text + "','" + this.score.Text + "');";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Saved");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
no need to use a MySqlDataReader
string constring = "Database=fillupform;Data Source=localhost;User Id=root;Password=''";
string Query = "INSERT INTO fillupform.fillupform (filename,instructor,time,score) VALUES (#filename,#instructor,#time, #score);";
using (MySqlConnection conDataBase = new MySqlConnection(constring))
{
using (MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase))
{
cmdDatabase.CommandType = CommandType.Text;
cmdDatabase.Parameters.AddWithValue("#filename", this.filename.Text);
cmdDatabase.Parameters.AddWithValue("#instructor", this.instructor.Text);
cmdDatabase.Parameters.AddWithValue("#time", this.timeanddate.Text);
cmdDatabase.Parameters.AddWithValue("#score", this.score.Text);
try
{
cmdDatabase.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I've been working on this program where it will pull accounts out of the database and will display them in a textbox I got this working so far but it will only pull the account from my database on the first row. Here is my code :
string myConnection = "datasource=xxxx;port=3306;username=xxxx;password=xxxx!";
string Query = "select * from xxx.xxx;";
MySqlConnection conDataBase = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
DataTable dt = new DataTable();
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sUsername = myReader.GetString("usernames");
string sPasswords = myReader.GetString("passwords");
nsTextBox1.Text = sUsername + ":" + sPasswords;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Also is there anyway so it will erase the old Username + Password and show the new one that is pulled?
Like this?:
nsTextBox1.Text += sUsername + ":" + sPasswords + Enviroment.NewLine;
Also, your TextBox needs to be multiline.
Must it be a TextBox? Why not use a ListBox?
I've tried this code:
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] =" + textBox1.Text;
OleDbConnection My_Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= c:\\Users\\Documents\\HotelCustomersOld.mdb");
My_Connection.Open();
OleDbCommand My_Command = new OleDbCommand(sql, My_Connection);
My_Command.ExecuteNonQuery();
Error: Data type mismatch in criteria expression, at the line:
My_Command.ExecuteNonQuery();
Use parametrized query to avoid all kind of errors
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] =?";
using(OleDbConnection My_Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= c:\\Users\\Documents\\HotelCustomersOld.mdb"))
{
My_Connection.Open();
OleDbCommand My_Command = new OleDbCommand(sql, My_Connection);
My_Command.Parameters.Add("#p1", textBox1.Text);
My_Command.ExecuteNonQuery();
}
In your case the Room NUmber field is of Text type so, you need to enclose the value in single quotes, but this is really wrong. You expose your code to maliciuos text written by your user inside the text box. A very simple and funny example here
Which type is your [Room Number] column? If it is a string then you have to write the value with inverted comma or quotation mark (I'm not sure which of both is used in Access).
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] = '" + textBox1.Text + "'";
To avoid SQL injektion you should use Parameters instead of the string operation.
public static void DeleteLine(string kv)
{
OleDbConnection myConnection = GetConnection();
string myQuery = "DELETE FROM Cloth WHERE [ClothName] = '" + kv + "'";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
finally
{
myConnection.Close();
}
}
try
{
OleDbConnection con = new OleDbConnection("provider = microsoft.ace.oledb.12.0;data source = E:\\Sohkidatabase\\Sohki.accdb");
con.Open();
str = "select * from compny_info where id=" + comboBox1.Text.Trim() + "";
com = new OleDbCommand(str, con);
OleDbDataReader reader = com.ExecuteReader();
if (reader.Read())
{
textBox1.Text = reader["regis_no"].ToString();
textBox2.Text = reader["comp_oner"].ToString();
textBox3.Text = reader["comp_name"].ToString();
textBox4.Text = reader["comp_add"].ToString();
textBox5.Text = reader["tin_no"].ToString();
textBox6.Text = reader["email"].ToString();
}
con.Close();
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
public static void DeleteLine(string kv) {
OleDbConnection myConnection = GetConnection();
string myQuery = "DELETE FROM Cloth WHERE [ClothName] = '" + kv + "'" ;
}