この記事には、Windows アプリからの MySQL データベースの操作を有効にするのに必要な手順が含まれています。 It also contains a small code snippet showing how you can interact with the database in code.
ヒント
AI アシスタンスを用いて、GitHub Copilot で MySQL 接続文字列を作成できます。
Set up your solution
This example can be used with any WPF, Windows Forms, WinUI 3, and UWP project to connect your Windows app to a MySQL database. Follow these steps to install the package and try out the example code to read data from an existing MySQL database.
- Open the Package Manager Console (View -> Other Windows -> Package Manager Console).
- Use the command
Install-Package MySql.Data
to install the NuGet package for the MySQL core class library.
This will allow you to programmatically access MySQL databases.
Note
MySQL Connector/NET version 6.4.4 or later is required to use the MySql.Data
package with Windows authentication.
Test your connection using sample code
The following is an example of connecting to and reading from a remote MySQL database. Note that the server address and database name will need to be customized.
const string M_str_sqlcon = "Server=myServerAddress;Database=myDataBase;IntegratedSecurity=yes;Uid=auth_windows;";
using (var mySqlCn = new MySqlConnection(M_str_sqlcon))
{
using (var mySqlCmd = new MySqlCommand("select * from table1", mySqlCn))
{
mySqlCn.Open();
using (MySqlDataReader mySqlReader = mySqlCmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (mySqlReader.Read())
{
Debug.WriteLine($"{mySqlReader.GetString(0)}:{mySqlReader.GetString(1)}");
}
}
}
}
Important
In production applications, connection information should be stored securely in app configuration (see Adding Azure App Configuration by using Visual Studio Connected Services). Connection strings and other secrets should not be hard-coded.
GitHub Copilot を使用した接続文字列の構築
GitHub Copilot を使用して、MySQL データベース用の接続文字列を構築できます。 要件に従って接続文字列を作成するようにプロンプトをカスタマイズできます。
次のテキストは、前のコード スニペットで示したような接続文字列を生成する Copilot Chat のサンプル プロンプトを示しています。
Show me how to create a MySQL connection string to a server named myServerAddress and a database called myDatabase. Use Windows authentication.
GitHub Copilot では AI を利用しているため、想定外のことや間違いが起こる可能性があります。 詳しくは、Copilot の FAQ をご覧ください。
Visual Studio と VS Codeでの GitHub Copilot
Related content
Windows developer