从c#连接到MemSQL

本文关键字:MemSQL 连接 | 更新日期: 2023-09-27 18:10:19

我是MemSQL数据库的新手,我在Linux Redhat V6上安装了MemSQL数据库服务器。我还创建了一个名为"测试"的测试数据库,用户名是:root,密码是:root我可以在本地连接到这个数据库,我也知道我可以使用MySQL提供程序ODBC从windows连接到MemSQL数据库。我试图从Windows连接到MemSQL,但我得到了一个错误(连接失败:驱动程序在"读取初始通信数据包"时失去了与MySQL服务器的连接)。我的问题是:是否有可能从Windows连接到MemSQL数据库?如果是,我如何使用c#做到这一点(我应该使用什么提供程序,配置,等等)。谢谢你

从c#连接到MemSQL

这看起来更像是网络/防火墙问题。最简单的检查方法是在客户端和服务器上禁用防火墙,看看是否一切正常。

MemSQL只是使用MySQL的兼容性,所以官方的MySQL c#客户端将工作良好。您可以从nuget安装:https://www.nuget.org/packages/MySql.Data/

PM> Install-Package MySql.Data

下面是MemSQL文档中测试插入的一个快速示例:

http://docs.memsql.com/latest/concepts/multi_insert_examples/c

using System;
using System.Data;
using System.Threading;
using System.Diagnostics;
using MySql.Data.MySqlClient;
namespace MemSQLTest {
  //Thread creates a connection and inserts for 1000 milliseconds
  public class WorkerThread {
    public static void Thread() {
      try {
        IDbConnection conn;
        conn = new MySql.Data.MySqlClient.MySqlConnection();
        conn.ConnectionString = "Server=127.0.0.1;Uid=root;Pwd=;";
        conn.Open();
        IDbCommand dbcmd = conn.CreateCommand();
        dbcmd.CommandText = "USE db";
        dbcmd.ExecuteNonQuery();
        dbcmd.CommandText = "INSERT INTO t VALUES (DEFAULT)";
        Stopwatch stop = new Stopwatch();
        stop.Start();
        while(stop.ElapsedMilliseconds < 1000)
        {
          dbcmd.ExecuteNonQuery();
        }
      } catch (Exception ex) {
          Console.WriteLine(ex.Message);
      }
    }
  }
  class MemSQLTest {
    static void Main(string[] args) {
      try {
        IDbConnection conn;
        conn = new MySql.Data.MySqlClient.MySqlConnection();
        conn.ConnectionString = "Server=127.0.0.1;Uid=root;Pwd=;";
        conn.Open();
        //Initialize database with auto increment table
        IDbCommand dbcmd = conn.CreateCommand();
        dbcmd.CommandText = "DROP DATABASE IF EXISTS db";
        dbcmd.ExecuteNonQuery();
        dbcmd.CommandText = "CREATE DATABASE db";
        dbcmd.ExecuteNonQuery();
        dbcmd.CommandText = "USE db";
        dbcmd.ExecuteNonQuery();
        dbcmd.CommandText = "CREATE TABLE t (id int primary key auto_increment)";
        dbcmd.ExecuteNonQuery();
        //Initialize threads
        Thread[] threads = new Thread[10];
        for(int i = 0; i < 10; i++)
        {
          threads[i] = new Thread(new ThreadStart(WorkerThread.Thread));
          threads[i].Start();
        }
        for(int i = 0; i < 10; i++)
        {
          threads[i].Join();
        }
        //Show select count(*) on auto increment table
        dbcmd.CommandText = "SELECT COUNT(*) FROM t";
        IDataReader reader = dbcmd.ExecuteReader();
        while(reader.Read()) {
          Console.WriteLine(reader["COUNT(*)"]);
        }
      } catch (Exception ex) {
        Console.WriteLine(ex.Message);
      }
    }
  }
}