个性化阅读
专注于IT技术分析

如何使用C#Winforms和XAMPP连接到MySQL

点击下载

本文概述

XAMPP是由Apache Friends开发的一个免费和开放源代码的跨平台Web服务器解决方案堆栈软件包, 主要由Apache HTTP Server, MariaDB数据库以及以PHP和Perl编程语言编写的脚本的解释器组成。

如果使用xampp, 你可能知道使用phpmyadmin的集成模块创建和维护数据库是多么容易。你可能会发现使用PHP很容易, 但是, 如果你具有.NET知识, 也可以开始使用它。

MySQL为连接器提供了一个简单的连接器, 使你可以从Winform执行对phpmyadmin的查询。

在本文中, 我们将学习如何使用C#中的winforms轻松访问在phpmyadmin中创建的数据库。

要求

  • Visual Studio(任何版本)。
  • MySQL .NET连接器扩展。
  • XAMPP发行版(我们假设你知道如何使用mysql和xampp)。

实现

要成功实现成功, 请执行以下步骤, 此任务比你想象的要容易:

  • 将对MySQL连接器的引用添加到Winform项目中。
  • 使用PHPMyAdmin在MySQL中创建数据库(忽略是否已有数据库)。
  • 开始执行查询。

将对MySQL连接器的引用添加到项目中

首先, 你必须在系统中安装.NET MySQL扩展, 因为我们稍后需要在项目中添加引用。你可以在MySQL的官方网站中选择最新版本之一。

在系统上安装mysql连接器扩展

你可以选择完整安装还是典型安装。

安装

安装后, 我们将像平时一样在Visual Studio中创建一个空的Winforms项目。

现在我们需要在项目中添加对mysql连接器的引用。打开项目后, 在Visual Studio的右上角找到解决方案资源管理器, 右键单击”引用”, 然后从上下文菜单中选择”添加引用”。

参考.NET C#

在显示的菜单中, 导航到”扩展”, 然后从列表中选择MySql.Data(MySql.Data.dll)复选框, 然后单击”确定”。

MySQL数据.net C#参考

现在, 我们将能够使用C#连接到MySQL执行查询。

在phpmyadmin(localhost)中创建测试数据库

如前所述, 我们假设你已经在系统上安装了Xampp, 并且知道如何使用它。

首先, 不要忘记在xampp面板中启用apache和mysql服务(建议在管理员模式下使用)。

Xampp菜单

现在, 在浏览器中导航到http:// localhost / phpmyadmin并转到数据库区域。

创建一个数据库(在本例中将测试数据库)并创建一个名为user的表。

PHPMyAdmin mySql表

注意

记住要对id字段启用autoincrementable选项, 否则每次插入一行时都需要添加一个id。

现在我们的数据库” test”包含至少一个表” user”, 我们可以开始执行查询。

使用C#连接和执行查询

有趣的来了 !我们将编写一些代码来与MySQL数据库进行交互。主要的, 不要忘记在类中添加引用的using语句:

using MySql.Data.MySqlClient;

你可以通过以下代码段了解连接的工作方式以及如何执行查询:

// Change the username, password and database according to your needs
// You can ignore the database option if you want to access all of them.
// 127.0.0.1 stands for localhost and the default port to connect.
string connectionString = "datasource=127.0.0.1;port=3306;username=root;password=;database=test;";
// Your query, string query = "SELECT * FROM user";

// Prepare the connection
MySqlConnection databaseConnection = new MySqlConnection(connectionString);
MySqlCommand commandDatabase = new MySqlCommand(query, databaseConnection);
commandDatabase.CommandTimeout = 60;
MySqlDataReader reader;
 
// Let's do it !
try
{
    // Open the database
    databaseConnection.Open();

    // Execute the query
    reader = commandDatabase.ExecuteReader();

    // All succesfully executed, now do something

    // IMPORTANT : 
    // If your query returns result, use the following processor :
    
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            // As our database, the array will contain : ID 0, FIRST_NAME 1, LAST_NAME 2, ADDRESS 3
            // Do something with every received database ROW
            string[] row = { reader.GetString(0), reader.GetString(1), reader.GetString(2), reader.GetString(3) };
        }
    }
    else
    {
        Console.WriteLine("No rows found.");
    }

    // Finally close the connection
    databaseConnection.Close();
}
catch (Exception ex)
{
    // Show any error message.
    MessageBox.Show(ex.Message);
}

就是这样!基本上, 你只需要更改查询并开始测试。你可以在此处阅读有关连接字符串和所有可用属性的更多信息。

查询的基本示例

在这些示例中, 我们将执行最基本的要执行的任务(CRUD):

表格插入

请注意, 我们将使用一个简单的listView组件(具有4列:id, 名字, 姓氏和地址), 3个textBox和2个Buttons。

创建

在以下代码段中, 我们将在测试数据库中创建一个寄存器:

private void SaveUser()
{
    string connectionString = "datasource=127.0.0.1;port=3306;username=root;password=;database=test;";
    string query = "INSERT INTO user(`id`, `first_name`, `last_name`, `address`) VALUES (NULL, '"+textBox1.Text+ "', '" + textBox2.Text + "', '" + textBox3.Text + "')";
    // Which could be translated manually to :
    // INSERT INTO user(`id`, `first_name`, `last_name`, `address`) VALUES (NULL, 'Bruce', 'Wayne', 'Wayne Manor')
    
    MySqlConnection databaseConnection = new MySqlConnection(connectionString);
    MySqlCommand commandDatabase = new MySqlCommand(query, databaseConnection);
    commandDatabase.CommandTimeout = 60;
    
    try
    {
        databaseConnection.Open();
        MySqlDataReader myReader = commandDatabase.ExecuteReader();
        
        MessageBox.Show("User succesfully registered");
   
        databaseConnection.Close();
    }
    catch (Exception ex)
    {
        // Show any error message.
        MessageBox.Show(ex.Message);
    }
}

显示

在以下代码段中, 我们将在列表视图中列出测试数据库中的所有用户(如果可用或在控制台中显示):

private void listUsers()
{
    string connectionString = "datasource=127.0.0.1;port=3306;username=root;password=;database=test;";
    // Select all
    string query = "SELECT * FROM user";

    MySqlConnection databaseConnection = new MySqlConnection(connectionString);
    MySqlCommand commandDatabase = new MySqlCommand(query, databaseConnection);
    commandDatabase.CommandTimeout = 60;
    MySqlDataReader reader;

    try
    {
        databaseConnection.Open();
        reader = commandDatabase.ExecuteReader();
        // Success, now list 

        // If there are available rows
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                                     ID                              First name                  Last Name                    Address
                Console.WriteLine(reader.GetString(0) + " - " + reader.GetString(1) + " - " + reader.GetString(2) + " - " + reader.GetString(3));
                // Example to save in the listView1 :
                //string[] row = { reader.GetString(0), reader.GetString(1), reader.GetString(2), reader.GetString(3) };
                //var listViewItem = new ListViewItem(row);
                //listView1.Items.Add(listViewItem);
            }
        }
        else
        {
            Console.WriteLine("No rows found.");
        }

        databaseConnection.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

更新

用id更新一行的字段:

private void updateUser()
{
    string connectionString = "datasource=127.0.0.1;port=3306;username=root;password=;database=test;";
    // Update the properties of the row with ID 1
    string query = "UPDATE `user` SET `first_name`='Willy', `last_name`='Wonka', `address`='Chocolate factory' WHERE id = 1";

    MySqlConnection databaseConnection = new MySqlConnection(connectionString);
    MySqlCommand commandDatabase = new MySqlCommand(query, databaseConnection);
    commandDatabase.CommandTimeout = 60;
    MySqlDataReader reader;

    try
    {
        databaseConnection.Open();
        reader = commandDatabase.ExecuteReader();
        
        // Succesfully updated

        databaseConnection.Close();
    }
    catch (Exception ex)
    {
        // Ops, maybe the id doesn't exists ?
        MessageBox.Show(ex.Message);
    }
}

删除

删除ID为(x)的行:

private void deleteUser()
{
    string connectionString = "datasource=127.0.0.1;port=3306;username=root;password=;database=test;";
    // Delete the item with ID 1
    string query = "DELETE FROM `user` WHERE id = 1";

    MySqlConnection databaseConnection = new MySqlConnection(connectionString);
    MySqlCommand commandDatabase = new MySqlCommand(query, databaseConnection);
    commandDatabase.CommandTimeout = 60;
    MySqlDataReader reader;

    try
    {
        databaseConnection.Open();
        reader = commandDatabase.ExecuteReader();
        
        // Succesfully deleted

        databaseConnection.Close();
    }
    catch (Exception ex)
    {
        // Ops, maybe the id doesn't exists ?
        MessageBox.Show(ex.Message);
    }
}

玩得开心 !

赞(0)
未经允许不得转载:srcmini » 如何使用C#Winforms和XAMPP连接到MySQL

评论 抢沙发

评论前必须登录!