C# - Mysql select queries not executing - c#

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

Related

error: the property connection has not initialized

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.

Connection must be open C#

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
}

Oracle not connecting to remote server with .Net 4.0

I have an issue connecting to an oracle database from my test server. Bellow is my code snippet.
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
private static string GetConnectionString()
{
String connString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=IP_Address)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=Service_Name)));User Id=hook;Password=Password;";
return connString;
}
private string ConnectingToOracle()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
try
{
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = connection.CreateCommand();
string sql = " select * from sgmp.web_portal1 where account_no= '" + customerIdField.Value.ToString().Trim() + "'";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Session["ClientName"] = (string)reader["Customer_Name"];
return (string)reader["Customer_Name"];
}
}
else
{
resp.Text = "Client ID '" + customerIdField.Value.ToString().Trim() + "' does not exist in records";
return "none";
}
return "none";
}
catch (OracleException ex)
{
resp.Text = ex.Message + " reasons ..";
return "mmm";
}
}
I got nothing as exception and I can't just connect.
Regards.
My first with Oracle after-all.
I found the solution here: http://support.microsoft.com/kb/255084 All I needed to do was step 1 to 5

How to connect remote database in asp.net using mysql?

protected void Button1_Click(object sender, EventArgs e)
{
try
{
string MyConString = "SERVER=http://10.54.3.208:8080/Ager/person;" + "DATABASE=agero;" + "UID=root;" + "PASSWORD=root;";
MySqlConnection con = new MySqlConnection(MyConString);
//MySqlConnection command = con.CreateCommand();
con.Open();
string s = "select * from boopathi where STU_ID =#sid and STU_PWD =#pwd";
MySqlCommand cmd = new MySqlCommand(s, con);
cmd.Parameters.AddWithValue("#sid", TextBox1.Text.ToString());
cmd.Parameters.AddWithValue("#pwd", TextBox2.Text.ToString());
cmd.ExecuteNonQuery();
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
Server.Transfer("WebForm1.aspx");
}
}
//close connection
con.Close();
}
catch (Exception ex)
{
Response.Write("An error occured: " + ex.Message);
}
}
In localhost it is working perfectly. Once I set my remote link instead of localhost. It's not connecting anymore. I am getting exception like Unable to connect to any of the specified MySQL hosts.
Try it:-
MySqlConnection c = new MySqlConnection("server=10.54.3.208; database=agero; uid=root; pwd=root");
OR
string MyConString = "SERVER=10.54.3.208;" + "DATABASE=agero;" + "UID=root;" + "Pwd=root;";
refer this link for more information MySQL Connector
I hope it may help you.
Try this one:
http://www.c-sharpcorner.com/uploadfile/camilord/connecting-to-remote-mysql-linux-server-using-visual-C-Sharp/
I hope this will solve your problem

error for insert and stored data in access 2013

i have this code for insert data into access 2013
after click in the save button data insert into dataGridView and show
and when stop program and restart this,data not stored in the DB.I've done a lot of searches but can't find the solution. my class code and my button save code
class DB
{
public static OleDbConnection con = new OleDbConnection();
static DB()
{
con.ConnectionString = "Provider=MICROSOFT.ACE.OLEDB.12.0; " +
"Data Source=|DataDirectory|//Phonebook-db.accdb;Persist Security Info=True";
}
public static void Insert(Person p1)
{
try
{
OleDbCommand cmd = con.CreateCommand();
con.Open();
string s = "INSERT INTO Industrialist (S_Name,S_Family,S_Telephone,S_Major)VALUES('" + p1.Name + "','" + p1.Family + "','" + p1.Telephone + "','" + p1.Major + "')";
cmd.CommandType = CommandType.Text;
cmd.CommandText = s;
cmd.ExecuteNonQuery();
con.Close();
System.Windows.Forms.MessageBox.Show("Record successfully Added");
}
catch (OleDbException exp) { MessageBox.Show(exp.ToString()); }
}
}
Person p = new Person();
p.Name = txtname.Text;
p.Family = txtfamily.Text;
p.Telephone = txttell.Text;
p.Major = txtmajor.Text;
DB.Insert(p);
txttell.Text = "";
txtmajor.Text = "";
txtname.Text = "";
txtfamily.Text = "";
List<Person> people = DB.GetPeople();
dataGridView1.DataSource = people;
Choose your ACCDB file listed in your project files, select Copy To Output Directory and set its value to Never (And remember that |DataDirectory| is a substitution strings that points (for ASP.NET projects) to APP_DATA, your record is inserted in the database copied in that directory.
Said that please consider to use a parameterized query to create an sql command, not string concatenations
try
{
OleDbCommand cmd = con.CreateCommand();
con.Open();
string s = "INSERT INTO Industrialist (S_Name,S_Family,S_Telephone,S_Major)VALUES(" +
"?,?,?,?)";
cmd.CommandText = s;
cmd.Parameters.AddWithValue("#p1",p.Name);
cmd.Parameters.AddWithValue("#p2",p.Family);
cmd.Parameters.AddWithValue("#p3",p.Telephone);
cmd.Parameters.AddWithValue("#p4",p.Major);
cmd.ExecuteNonQuery();
con.Close();
System.Windows.Forms.MessageBox.Show("Record successfully Added");
}
catch (OleDbException exp) { MessageBox.Show(exp.ToString()); }
Of course do not close the connection before executing the command.
Another point to change is the usage pattern of your connection. Do not create a global connection and keep it around for the lifetime of your application. Simply create and use it when needed and close/dispose immediately after
using(OleDbConnection con = new OleDbConnection("Provider=MICROSOFT.ACE.OLEDB.12.0; " +
"Data Source=|DataDirectory|//Phonebook-db.accdb;" +
"Persist Security Info=True"))
{
try
{
OleDbCommand cmd = con.CreateCommand();
....
}
} // <- Here at the closing brace the connectio will be close and disposed

Categories

Resources