Connecting C# to a remote MySQL database - c#

I am trying to connect a C# application to my MySQL database located in a remote server. When I try to execute this simple program, I get the following error: sqlException was unhandled
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("user id=student_abdo;password=XXXXXX;server=178.239.167.XXX;Trusted_Connection=yes;database=student_sms;connection timeout=30");
SqlCommand com = new SqlCommand("UPDATE `sms` SET `id`=23 WHERE `sms`='hi'",con);
com.CommandType = CommandType.Text;
con.Open();
com.ExecuteNonQuery();
con.Close();
}

The SqlClient namespace is for connecting to Microsoft SqlServer databases. If you want to work with MySql, you'll need to find an ADO.NET implementation (3rd party) or determine if there is a way to make it work with OleDb/Odbc.
UPDATE
Apparently, MySql provides its own ADO.NET driver for getting the job done.

As Brian pointed out, you are using the wrong provider. Also, your connection string is wrong. It should read
"Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
You can reference this site for all of the different connection string types for mysql

Here is what you need to download
Keep in mind that Classes for working with MySql in .NET are mostley the same as working with MSSQL with exception that they have My... prefix
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("userid=student_abdo;password=XXXXXX;server=178.239.167.XXX;Trusted_Connection=yes;database=student_sms;connection timeout=30");
MySqlCommand com = new MySqlCommand("UPDATE `sms` SET `id`=23 WHERE `sms`='hi'",con);
com.CommandType = CommandType.Text;
con.Open();
com.ExecuteNonQuery();
con.Close();
}

first of all, you know what is forms of connect string and then established the connection with the database.
bb rec
private void btnretrive_Click(object sender, EventArgs e)
{
string cs = "server=localhost;user id=root;database=world;";
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmd = new SqlCommand("select * from world;",conn);
SqlDataReader reader = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
dataGridView1.DataSource = table;
conn.Close();
}

Related

Asp.net C# & MySQL, (The Read method cannot be called when another read operation is pending.)

Problems:
1: The Read method cannot be called when another read operation is pending.
2: There is already an open DataReader associated with this Connection which must be closed first.
I have used Asp.net c# and MySql to develop my project. When I did publish it, I faced a problem. The problem is when more than one user open the website, the MySql connection stop working. There is a sample of my code.
public partial class ConTest : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection("Server= mysql-85112-0.cloudclusters.net; port=11923; Database=Test; Uid=xxxx; Pwd=xxxx;");
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{
cmd.Connection = con;
Database.con.Close();
Database.con.Open();
cmd.CommandText = "select s_name from students_info";
dr = cmd.ExecuteReader();
while (dr.Read())
{
Label1.Text = dr[0].ToString();
}
Database.con.Close();
}
}
Don't share MySqlConnection objects. Create a new one when you need it, and close it automatically by using a using declaration:
protected void Page_Load(object sender, EventArgs e)
{
using var connection = new MySqlConnection("Server= mysql-85112-0.cloudclusters.net; port=11923; Database=Test; Uid=xxxx; Pwd=xxxx;");
using var command = new MySqlCommand("select s_name from students_info", connection);
connection.Open();
using var dr = command.ExecuteReader();
if (dr.Read())
{
Label1.Text = dr.GetString(0);
}
}

error while connecting to mysql in C# asp.net

I have an error while connecting my project into mysql database so i have added the code bellow to my button to fetch all rows and display it in a gridView
protected void Button1_Click(object sender, EventArgs e)
{
MySqlConnection myconn = new MySqlConnection("server=localhost;uid=root;password=;database=y;");
string strSQL = "select * from welcome";
myconn.Open();
MySqlDataAdapter mydata = new MySqlDataAdapter(strSQL, myconn);
MySqlCommandBuilder cBuilder = new MySqlCommandBuilder(mydata);
System.Data.DataSet ds = new System.Data.DataSet();
mydata.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
myconn.Close();
}
When running the the app it shows an error in myconn.Open();
An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: The host localhost does not support SSL connections.
and it pointed to myconn.Open();
change myconn to :
MySqlConnection myconn = new MySqlConnection("server=localhost;uid=root;password=;database=y;sslmode=none");
Make sure that you are adding sslmode=none in myconn
better try with Entity Frame work
Add ADO.NET Entity model,If will ask to connect db and give some name(ex :userentities)
Then, use below code in your coding
userentities context = new userentities();
protected void Button1_Click(object sender, EventArgs e)
{
using (var dbTransactionContext = context.Database.BeginTransaction())
{
//then do the operation
}
}
It's really easy
or other wise follow these steps
1. add your connection string in web config
<add name="UserContext" connectionString="server=localhost;User Id=root;password='';database=databasename;convert zero datetime=True" providerName="MySql.Data.MySqlClient" />
Add follow codes in your code
private MySqlConnection con;
con = new MySqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["UserContext"].ConnectionString;
con.Open();

Application freeze at connection.open()

I created a Firebird database and successfully connected to it via Visual Studio Server Explorer. Now I want to test it through code, so I made a simple form that - on a button press - changes a label text to a value from the database. Here is the code
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("data source=localhost;initial catalog=D:\\poslovanje\\POSLOVANJE.FDB;user id=SYSDBA");
SqlCommand cmd = new SqlCommand("SELECT ID FROM USERS", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
label3.Text = dr[0].ToString();
}
con.Close();
}
Problem is my application just freezes when it comes to con.Open();
I have also tried this connection string:
User=SYSDBA;Password=masterkey;Database=D:\\poslovanje\\poslovanje.fdb;Data Source=localhost;
It's basic beginners mistake, i need to use FbConnection and FbCommand, not Sql

Not sure how to initialise the database connection

I am trying to insert into my SQL database table called Questions, whenever I click on the button the error below comes up and I'm not sure how to solve this problem as I thought I only needed to open the database connection then close it afterwards?
Any help would be very helpful.
private void button1_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command1 = new SqlCommand("INSERT INTO Questions ([Question Type]) VALUES (1)");
command1.ExecuteNonQuery();
connect.Close();
}
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: ExecuteNonQuery: Connection property has not been initialized.
Error message is clear;
You did not connect your SqlCommand and SqlConnection. Use your connection as a second parameter in your command like;
SqlCommand command1 = new SqlCommand("INSERT INTO Questions ([Question Type]) VALUES (1)",
connect);
Or you can use CreateCommand when you create your SqlCommand based on your connection. Also use using statement to dispose your connection and command automaticly instead of calling .Close() method manually.
Best way possible;
private void button1_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
using(var connect = new SqlConnection(connectionString))
using(var command1 = connect.CreateCommand())
{
command1.CommandText = "INSERT INTO Questions ([Question Type]) VALUES (1)";
connect.Open();
command1.ExecuteNonQuery();
}
}

Track Database Status Change sql server

I want to Track database status changed in sql server . in my solution ,I have a database that is offline due to restore from primary server .
i want to get hint in my application(C#) when database is offline and when is online. (like sql notification event) .
Thanks .
One way is to check the state of the database using a timer from your application
private void timer1_tick(object sender,EventArgs e)
{
if(CheckDatabaseState() == "ONLINE")
MessageBox.Show("db is online");
else
MessageBox.Show("db is NOT online");
}
Public string CheckDatabaseState()
{
string Constr = #"Data Source=.\SQLEXPRESS;Integrated Security=True;Initial Catalog=master;";
string sql = string.Format("SELECT Name, state_desc FROM sys.databases where name = '{0}'", dbName);
SqlConnection conn;
SqlCommand comm;
SqlDataAdapter adapter;
DataSet ds = new DataSet();
conn = new SqlConnection(Constr);
comm = new SqlCommand(sql, conn);
adapter = new SqlDataAdapter(comm);
adapter.Fill(ds);
return ds.Tables[0]["state_desc"].ToString();
}
Let me know if this helps,

Categories

Resources