Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 连接mysql数据库

作者:剑歌踏天下   发布日期:2026-05-19   浏览:23

using System;
using MySql.Data.MySqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "server=localhost;user=root;database=testdb;port=3306;password=yourpassword";

        try
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                Console.WriteLine("Connecting to MySQL...");
                conn.Open();
                Console.WriteLine("Connection Opened!");

                // Create a command and set its connection to the MySQL connection.
                MySqlCommand cmd = new MySqlCommand("SELECT * FROM users", conn);

                // Execute the command and obtain a data reader.
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine(reader["name"] + ", " + reader["email"]);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: '" + ex.Message + "'");
        }
    }
}

解释说明:

  1. 引入命名空间using MySql.Data.MySqlClient; 引入了用于连接和操作 MySQL 数据库的类。
  2. 连接字符串connectionString 包含了连接到 MySQL 数据库所需的信息,如服务器地址、用户名、密码、数据库名称等。
  3. 打开连接:使用 MySqlConnection 类创建一个连接对象,并调用 Open() 方法打开连接。
  4. 执行查询:使用 MySqlCommand 创建一个 SQL 查询命令,并通过 ExecuteReader() 方法执行查询,返回一个 MySqlDataReader 对象。
  5. 读取数据:通过 while (reader.Read()) 循环读取查询结果,并输出每行数据。
  6. 异常处理:使用 try-catch 块捕获并处理可能发生的异常。

上一篇:c#连接mysql数据库

下一篇:c# mysqlhelper

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站