A MySqlConnection object represents a session to a MySQL Server
data source. When you create an instance of MySqlConnection, all
properties are set to their initial values. For a list of these
values, see the MySqlConnection constructor.
If the MySqlConnection goes out of scope, it is not closed.
Therefore, you must explicitly close the connection by calling
Close or Dispose.
The following example creates a MySqlCommand and a
MySqlConnection. The MySqlConnection is opened and set as the
Connection for the MySqlCommand. The example then calls
ExecuteNonQuery, and closes the connection. To accomplish
this, the ExecuteNonQuery is passed a connection string and a
query string that is an SQL INSERT statement.
The following example shows how to use the MySqlConnection
class with VB.NET:
Public Sub InsertRow(myConnectionString As String)
' If the connection string is null, use a default.
If myConnectionString = "" Then
myConnectionString = "Database=Test;Data Source=localhost;User Id=username;Password=pass"
End If
Dim myConnection As New MySqlConnection(myConnectionString)
Dim myInsertQuery As String = "INSERT INTO Orders (id, customerId, amount) Values(1001, 23, 30.66)"
Dim myCommand As New MySqlCommand(myInsertQuery)
myCommand.Connection = myConnection
myConnection.Open()
myCommand.ExecuteNonQuery()
myCommand.Connection.Close()
End Sub
The following example shows how to use the MySqlConnection
class with C#:
public void InsertRow(string myConnectionString)
{
// If the connection string is null, use a default.
if(myConnectionString == "")
{
myConnectionString = "Database=Test;Data Source=localhost;User Id=username;Password=pass";
}
MySqlConnection myConnection = new MySqlConnection(myConnectionString);
string myInsertQuery = "INSERT INTO Orders (id, customerId, amount) Values(1001, 23, 30.66)";
MySqlCommand myCommand = new MySqlCommand(myInsertQuery);
myCommand.Connection = myConnection;
myConnection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}