通过 C# 连接到 MySQL 服务器 [英] Connecting to MySQL server via C#

查看:38
本文介绍了通过 C# 连接到 MySQL 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,用于连接到 MySQL 服务器并获取一些信息:

This is my code that is meant to connect to a MySQL server and fetch some info:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace test_MLDropCopy
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "server=xxxxx;uid=xxxxx;pwd=xxxxx";

            SqlConnection mySqlConnection = new SqlConnection(connectionString);

            string selectString = "select Symbol from today_positions.all_rttp where ServiceName like 'ML%' and ID = 137800";

            SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

            mySqlConnection.Open(); 

            mySqlCommand.CommandText = selectString;

            SqlDataReader myReader = null;

            myReader = mySqlCommand.ExecuteReader();

            string Symbol = myReader["Symbol"].ToString();

            Console.WriteLine(Symbol);

            mySqlConnection.Close();


        }
    }
}

但是,这是我得到的错误:

However, this is the error I'm getting:

Unhandled Exception: System.Data.SqlClient.SqlException: A network-related or in
stance-specific error occurred while establishing a connection to SQL Server. Th
e server was not found or was not accessible. Verify that the instance name is c
orrect and that SQL Server is configured to allow remote connections. (provider:
 Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

我已经仔细检查了我正在使用的登录凭据.是我的代码有问题,还是数据库端的问题(离线、权限不足等)?

I have double checked the login credentials I am using. Is there a problem in my code, or is the problem from the database end (offline, inadequate permissions etc.) ?

推荐答案

SqlConnection 类不是数据库连接的基类;其目的是连接到 MS SQL Server DB.你想要的是一个基本的 OleDbConnection 或 OdbcConnection;如果您的 MySql 实例支持,我会使用 OleDb.

The SqlConnection class is not the base class for a DB connection; its purpose is to connect to MS SQL Server DBs. What you want is a basic OleDbConnection or OdbcConnection; I would use OleDb if your MySql instance supports it.

这篇关于通过 C# 连接到 MySQL 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆