Skip to content

Commit 162bc52

Browse files
committed
Add a MySQL connection tutorial.
1 parent 77abf91 commit 162bc52

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
---
2+
date: 2019-11-18
3+
menu:
4+
main:
5+
parent: tutorials
6+
title: Connect to MySQL
7+
customtitle: How to Connect to MySQL from .NET Core
8+
weight: 3
9+
---
10+
11+
# How to Connect to MySQL from .NET Core
12+
13+
This tutorial will teach you how to connect to MySQL from .NET Core using C#.
14+
15+
## 1. Install MySqlConnector
16+
17+
First, install the [MySqlConnector NuGet package](https://www.nuget.org/packages/MySqlConnector/). From
18+
a command prompt, run:
19+
20+
```
21+
dotnet add package MySqlConnector
22+
```
23+
24+
Or right-click your project, choose **Manage NuGet Packages...**, in the **Search** box enter
25+
`MySqlConnector`, and install the package in your project.
26+
27+
## 2. Connection String
28+
29+
A typical connection string for MySQL is:
30+
31+
```
32+
server=YOURSERVER;user=YOURUSERID;password=YOURPASSWORD;database=YOURDATABASE
33+
```
34+
35+
Replace the values in that string with the appropriate settings for your database. For more advanced
36+
settings, see [Connection Options](/connection-options/).
37+
38+
If you are using ASP.NET Core, your connection string will usually be stored in `appsettings.json`:
39+
40+
```json
41+
{
42+
....
43+
"ConnectionStrings": {
44+
"Default": "server=YOURSERVER;user=YOURUSERID;password=YOURPASSWORD;database=YOURDATABASE"
45+
}
46+
}
47+
```
48+
49+
## 3. Configure Service (ASP.NET Core)
50+
51+
If using ASP.NET Core, you will want to register a database connection in `Startup.cs`:
52+
53+
```csharp
54+
public void ConfigureServices(IServiceCollection services)
55+
{
56+
// ...
57+
services.AddTransient<MySqlConnection>(_ => new MySqlConnection(Configuration["ConnectionStrings:Default"]));
58+
}
59+
```
60+
61+
## 4. Open and Use the Connection
62+
63+
In ASP.NET Core, the `MySqlConnection` object will be dependency-injected into your `Controller` class. For
64+
other kinds of projects, you may need to explicitly create the connection:
65+
66+
```csharp
67+
using var connection = new MySqlConnection(yourConnectionString);
68+
```
69+
70+
You can then open the connection and execute a query:
71+
72+
```csharp
73+
await connection.OpenAsync();
74+
75+
using var command = new MySqlCommand("SELECT field FROM table;", connection);
76+
using var reader = await command.ExecuteReaderAsync();
77+
while (await reader.ReadAsync())
78+
{
79+
var value = reader.GetValue(0);
80+
// do something with 'value'
81+
}
82+
```

0 commit comments

Comments
 (0)