So heres my code
string connString = "Server=localhost;Database=rfid;Uid=root;password=;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from users WHERE id_no = " + this.id_no.Text;
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
label1.Text = "ID Number: " + reader["id_no"].ToString();
label2.Text = "Name: " + reader["name"].ToString();
label3.Text = "User type: " + reader["user_type"].ToString();
id_no.Text = "";
}
It says Connection must be valid and open.
I already checked my Firewall and set it off. apache and mysql port running. what is the possible error in my code?
You should put all IDisposable classes in a using statement, this includes your connection object. Do it like this, which includes the disposal and opening of the connection:
using (var conn = new SqlConnection(connString))
{
conn.Open();
//Do Work
}
Related
The program I have been creating takes a SQL query as a string parameter and passes it to a method where it is then executed. I am able to open my mysql connection for each query, but for some reason I am unable to run any select statements (I have tried both ExecuteReader and ExecuteScalar).
However, when I run an ExecuteNonQuery, it runs it fine. I am able to verify the insert statement worked from the ExecuteNonQuery.
I currently have the same database up in a SQLyog, using the exact same connection information. While the select statement is running, I am simultaneously running "SHOW FULL PROCESSLIST" and I do not see the query being run. Here is the code I have:
private void buttonConnect_Click(object sender, EventArgs e)
{
string tmp = mysqlSelectScalar("select NAME from PRESIDENTS where name like '%trump%';");
string tmp = mysqlSelectScalar("select COUNT(*) from project.PRESIDENTS;");
mysqlnonQuery("insert into PRESIDENTS (ID,NAME) VALUES ('66','TEST');");
}
public string mysqlSelectScalar(string query)
{
string connString = "server=" + textBoxHostname.Text + ";user=" + textBoxUsername.Text + "; password=" + textBoxPW.Text + ";port=" + textBoxPort.Text + ";database=" + textBoxDB.Text + ";RespectBinaryFlags = false;CharSet=utf8;";
MySqlConnection cnn = new MySqlConnection(connString);
string result = "";
try
{
MessageBox.Show(query);
MySqlCommand cmd = new MySqlCommand(query, cnn);
using (cnn)
{
cnn.Open();
cmd.CommandTimeout = 10;
result = Convert.ToString(cmd.ExecuteScalar());
}
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("COULD NOT CONNECT TO DATABASE: " + ex.ToString());
}
return result;
}
public void mysqlnonQuery(string query)
{
string connString = "server=" + textBoxHostname.Text + ";user=" + textBoxUsername.Text + "; password=" + textBoxPW.Text + ";port=" + textBoxPort.Text + ";database=" + textBoxDB.Text + ";RespectBinaryFlags = false;CharSet=utf8;";
MySqlConnection cnn = new MySqlConnection(connString);
string result = "";
try
{
MessageBox.Show(query);
MySqlCommand cmd = new MySqlCommand(query, cnn);
using (cnn)
{
cnn.Open();
cmd.ExecuteNonQuery();
}
cnn.Close();
connStatus = 0;
}
catch (Exception ex)
{
MessageBox.Show("COULD NOT CONNECT TO DATABASE: " + ex.ToString());
connStatus = 1;
}
}
private void outputTable(string query)
{
try
{
string connString = "server=" + textBoxHostname.Text + ";user=" + textBoxUsername.Text + "; password=" + textBoxPW.Text + ";port=" + textBoxPort.Text + ";database=" + textBoxDB.Text + ";RespectBinaryFlags = false;CharSet=utf8;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataAdapter adpt = new MySqlDataAdapter();
conn.Open();
cmd.CommandTimeout = 5;
MySqlDataAdapter sqladapter = new MySqlDataAdapter(query, conn);
DataSet DS = new DataSet();
sqladapter.Fill(DS);
//the above command is what times out. Everything before runs fine
dataGridViewOutput.DataSource = DS.Tables[0];
MessageBox.Show("dataGridViewOutput.DataSource = DS.Tables[0];");
conn.Clone();
}
catch (Exception ex)
{
richTextBoxOutput.Text = ex.ToString();
}
}
The error message I am getting is from a timeout:
System.TimeoutException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I am sure that the connection string is working because I am able to run the mysqlnonQuery method, and when I put print statements in the mysqlSelectScalar method I saw I was able to get past the opening of the connection.
I should also specify that the table I am selecting from is only 45 records, and I am able to run the same select queries from the mysql command line, which complete in about 0.01 seconds.
This code is also being re-purposed from an older project I was working on, with the exact same mysqlSelectScalar method, and was working perfectly.
Any kind of help would be much appreciated.
using System;
using MySql.Data.MySqlClient;
namespace RetrieveCars
{
class Program
{
static void Main(string[] args)
{
string cs = #"server=localhost;userid=dbuser;password=s$cret;database=testdb";
using var con = new MySqlConnection(cs);
con.Open();
string sql = "SELECT * FROM cars";
using var cmd = new MySqlCommand(sql, con);
using MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine("{0} {1} {2}", rdr.GetInt32(0), rdr.GetString(1),
rdr.GetInt32(2));
}
}
}
}
Using this earlier question I need a bit of help
Using the second answer in the above link I had to update it for MySQL
private void btLogin_Click(object sender, EventArgs e)
{
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
using (var con = new MySqlConnection(connectionString));
{
using (var command = new MySqlCommand(connection = con))
{
con.Open();
command.CommandText = #"SELECT level FROM userTable WHERE user=#username, password=#password";
command.Parameters.AddWithValue("#username", lbUser.Text);
command.Parameters.AddWithValue("#password", tbPassword.Text);
var strLevel = command.ExecuteScalar();
if (strLevel == DBNull.Value || strLevel == null)
{
MessageBox.Show("Invalid username or password");
return;
}
else
{
MessageBox.Show("Successfully login");
Hide(); // hide this form and show another form
}
}
}
}
Everything looks good BUT this
using (var con = new MySqlConnection(connectionString));
{
using (var command = new MySqlCommand(connection = con))
{
con.Open();
It says that con doesn't exist. I don't know Using that well to see the problem.
The first parameter to the MySqlCommand constructor is the command text. It should work if you change your code to the following:
con.Open();
using (var command = new MySqlCommand())
{
command.Connection = con;
command.CommandText = #"SELECT level FROM userTable WHERE user=#username AND password=#password";
I'm working on a project. i've built a form by using visual studio express 2012 for desktop window and i'm programming in c#. here is a function that i want to use in a button event:
void connect()
{
//chaine_connexion="Data Source=MILLIONNAIRE-PC\\ITS4_2017;Initial Catalog=TP_ITS4_2017;User ID=sa;Password=***********"
string chaine = GestionEnquete.Properties.Settings.Default.chaine_connexion;
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = chaine;
cnn.Open();
// test the state of the connection
if (cnn.State == System.Data.ConnectionState.Open)
MessageBox.Show("Connexion established");
else
MessageBox.Show("Connexion not established");
//déclare an object SqlCommand type
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select count(*) from Agent" +
"where codeAgent='" + TXT_LOGIN.Text.Trim() + "'" +
"and motdepasse = '" + PW_PASSWORD.Password + "'";
//cmd.Connection = cnn;
int resultat = cmd.ExecuteNonQuery();
if (resultat > 0)
{
MessageBox.Show("the user exist in the database");
Equipe a = new Equipe();
a.Show();
Hide();
}
else
MessageBox.Show("no user");
cnn.Close();
}
when i fill the form by adding a codeAgent and a password in TXT_LOGIN and PW_PASSWORD textbox, i received these messages:
Connexion established
error: the property connection has not initialized
Now when a put cmd.Connection = cnn; just before int resultat = cmd.ExecuteNonQuery();, visual studio send the error:
Execution error: incorrect syntaxe near '='.
Please i need your help.
There's a missing space after Agent:
cmd.CommandText = "select count(*) from Agent" + ...
This leads to the SQL command select count(*) from Agentwhere... causing this syntax error.
Just add a space and it should work as expected:
cmd.CommandText = "select count(*) from Agent " +
But your code is vulnerable to SQL-Injection.
You should read about parameterized queries.
I am trying to update my database while reading data from it, but the reader gets closed and it throws the exception that it can''t read wen reader is closed. Is the update.ExecuteNonQuery() closing the reader method?
If i get rid of linescon.Close(); con.Open(); i get There is already an open DataReader associated with this Connection which must be closed first.
So how can i update my database records while keep the reading opened?
{
public class MySqlReadUpdate
{
public int Id { get; set; }
public string Notes { get; set; }
}
static void Main()
{
List<MySqlReadUpdate> dbData = new List<MySqlReadUpdate>();
var config = "server=localhost;user id=root; database=restaurants; pooling=false;SslMode=none;Pooling=True";
MySqlConnection con = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT id, notes FROM customers";
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
MySqlReadUpdate newMySqlReadUpdate = new MySqlReadUpdate();
newMySqlReadUpdate.Id = (int)reader["id"];
newMySqlReadUpdate.Notes = (string)reader["notes"];
string note = newMySqlReadUpdate.Notes;
var notesplit = note.Split(' ', '\n')[1];
dbData.Add(newMySqlReadUpdate);
Console.WriteLine(newMySqlReadUpdate.Id);
Console.WriteLine(newMySqlReadUpdate.Notes);
Console.WriteLine(note);
Console.WriteLine(notesplit);
con.Close();
con.Open();
string query2 = "UPDATE customers SET notes='" + notesplit + "' WHERE id='" + newMySqlReadUpdate.Id + "';";
MySqlCommand update = new MySqlCommand(query2, con);
update.ExecuteNonQuery();
}
con.Close();
Console.WriteLine("Finished!");
Console.Read();
}
}
}
You cannot close a connection like you are, because the data reader depends on it. Once you call con.Close you break it. That's why you see an exception the next time it gets to reader.Read().
What you want is to add MultipleActiveResultSets=True in the configuration string; however, as we discussed in the comments it's apparently still not supported in MySQL. Therefore, the answer is two connection instances.
List<MySqlReadUpdate> dbData = new List<MySqlReadUpdate>();
var config = "server=localhost;user id=root;database=restaurants;pooling=false;SslMode=none";
MySqlConnection con = new MySqlConnection(config);
MySqlConnection cmdCon = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT id, notes FROM customers";
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
cmdCon.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
MySqlReadUpdate newMySqlReadUpdate = new MySqlReadUpdate();
newMySqlReadUpdate.Id = (int)reader["id"];
newMySqlReadUpdate.Notes = (string)reader["notes"];
string note = newMySqlReadUpdate.Notes;
var notesplit = note.Split(' ', '\n')[1];
dbData.Add(newMySqlReadUpdate);
Console.WriteLine(newMySqlReadUpdate.Id);
Console.WriteLine(newMySqlReadUpdate.Notes);
Console.WriteLine(note);
Console.WriteLine(notesplit);
string query2 = "UPDATE customers SET notes='" + notesplit + "' WHERE id='" + newMySqlReadUpdate.Id + "';";
MySqlCommand update = new MySqlCommand(query2, cmdCon);
update.ExecuteNonQuery();
}
con.Close();
cmdCon.Close();
Console.WriteLine("Finished!");
Console.Read();
I would recommend that you also modify your code to use using statements or wrap things in try-finally blocks.
I'm having trouble with a SQL query:
using (SqlConnection conn = new SqlConnection("user id=user;" + "password=pass;" + "server=server;" + "database=db;"))
{
using (SqlCommand comm = new SqlCommand(#"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'"))
{
conn.Open();
comm.Connection = conn;
MessageBox.Show("TEST: {0}", Convert.ToString((int)comm.ExecuteScalar()));
}
}
I'm expecting to get an int in the message box conveying the number of rows that BolagsID occurs in. But I get 0 every time. I've tried the query in SQL Server Management Studio and it works fine there. What am I doing wrong/missing?
EDIT:
This works, but now I don't know how to parameterize the values:
string query = #"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = " + BolagsID;
ADODB.Connection conn2 = new ADODB.Connection();
ADODB.Recordset rs = new ADODB.Recordset();
string strConn = "Provider=...;Data Source=...;Database=...;User Id=...;Password=...";
conn2.Open(strConn);
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic;
rs.Open(query, conn2);
if (rs.Fields[0].Value > 0)
...stuff...
Like others are saying, parameters are a good idea. Here's something to get you started:
string query = #"SELECT Count(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = #BolagsID";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#BolagsID", SqlDbType.NVarChar).Value = BolagsID;
conn.Open();
MessageBox.Show("TEST: {0}", Convert.ToString((int)cmd.ExecuteScalar()));
conn.Close();
}
Basically a 0 is returned if there is an error in your query, so even though SSMS is smart enough to resolve it, the sql command isn't.
A quick way to make sure that everything else is working okay is to change the query to just "SELECT Count(*) FROM [CompaniesDB].[dbo].[Companies]". If that doesn't work then the issue could lie with your database connection (permissions?) or something else.
Try assigning SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'" to a string str as follows
string str =#"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'";
using (SqlConnection conn = new SqlConnection("user id=user;" + "password=pass;" + "server=server;" + "database=db;"))
{
using (SqlCommand comm = new SqlCommand(str))
{
conn.Open();
comm.Connection = conn;
MessageBox.Show("TEST: {0}", Convert.ToString((int)comm.ExecuteScalar()));
}
}
Then do a watch/quickwatch on str's value to get the exact query that is getting run and then run the same query in Sql Managment studio. If you get 0 in Sql Management Studio as well, then the problem is that the data is just not there.
I tried a lot of stuff before trying out a whole different approach. This gives me the result I want:
string query = #"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = " + BolagsID;
ADODB.Connection conn2 = new ADODB.Connection();
ADODB.Recordset rs = new ADODB.Recordset();
string strConn = "Provider=...;Data Source=...;Database=...;User Id=...;Password=...";
conn2.Open(strConn);
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic;
rs.Open(query, conn2);
if (rs.Fields[0].Value > 0)
...stuff...
Note that both connection and record set are closed outside of this code snippet.