查询在 phpMyAdmin 中工作正常,但在应用程序中则不行(C#)

发布于 2024-11-29 06:53:54 字数 686 浏览 2 评论 0原文

在 SO 和其他地方有一些类似的问题,但主要是关于 php 的,我不明白。我正在尝试恢复一个有 62 个表的数据库,如下所示:

string query = @"SET SQL_MODE= 'NO_AUTO_VALUE_ON_ZERO'; CREATE DATABASE " + dbName + " DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE " + dbName + ";" + Environment.NewLine;

using (StreamReader reader = File.OpenText("C:\b.sql"))
{
    string line = reader.ReadToEnd();
    query += line; //almost 1700 lines.
}
// upto this i get the query correctly which works fine in phpMyAdmin.

MySqlCommand c = new MySqlCommand(query, conn);
c.ExecuteReader();
//but when I execute, throws: "Fatal error encountered during command execution."

为什么会这样?如果它是查询长度的余弦,那么我如何从应用程序执行如此大的查询?

There are a few similar questions on SO and elsewhere but mostly with php and I do not understand that. I'm trying to restore a database with a 62 tables like this:

string query = @"SET SQL_MODE= 'NO_AUTO_VALUE_ON_ZERO'; CREATE DATABASE " + dbName + " DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE " + dbName + ";" + Environment.NewLine;

using (StreamReader reader = File.OpenText("C:\b.sql"))
{
    string line = reader.ReadToEnd();
    query += line; //almost 1700 lines.
}
// upto this i get the query correctly which works fine in phpMyAdmin.

MySqlCommand c = new MySqlCommand(query, conn);
c.ExecuteReader();
//but when I execute, throws: "Fatal error encountered during command execution."

Why is this so? If it's 'cos of the length of the query, then how can I execute such large queries from the application?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

影子的影子 2024-12-06 06:53:54

尝试检查错误:

List<string> query = new List<string>(){
        "SET SQL_MODE= 'NO_AUTO_VALUE_ON_ZERO';",
        string.Format("CREATE DATABASE `{0}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;", dbName),
        string.Format("USE `{0}`;", dbName)}; // error string.Format("USE `{0}`;{1}", dbName)
/*    
using (StreamReader reader = File.OpenText("C:\b.sql"))
{
    while (reader.Peek() >= 0)
        query.Add(reader.ReadLine());
}
*/

using (StreamReader reader = File.OpenText("C:\b.sql"))
{
    string lines = reader.ReadToEnd();
    string[] alines = lines.Split(';');
    foreach(string q in alines) 
            query.Add(q);
}

foreach (string command in query)
{
    try
    {
        using (MySqlCommand c = new MySqlCommand(command, conn))
        {
            c.ExecuteReader();
            Console.WriteLine(string.Format("OK Command: {0}", command));
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(string.Format("Error: {0}. Command: {1}", ex.Message, command));
        break;
    }
}

编辑

为了获得更好的性能,您可以使用此类。我还没试过,希望效果好:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.IO;

namespace MySQLHelperTest
{
    public class MySQLTestingQuery
    {
        public MySqlConnection MyConnection { get; set; }
        public string FileSql { get; set; }
        public List<string> PreviousQuerys { get; set; }
        public List<string> CorrectQuerys { get; private set; }
        public string ErrorQuery { get; private set; }

        public MySQLTestingQuery()
        {
            this.CorrectQuerys = new List<string>();
            this.ErrorQuery = string.Empty;
        }

    public void Start()
    {
        FileInfo file = new FileInfo(this.FileSql);
        if (!file.Exists)
            throw new ApplicationException(string.Format("nonexistent file: '{0}'", this.FileSql));

        if (this.PreviousQuerys != null)
            foreach (string command in this.PreviousQuerys)
                this.RunMySQLCommand(command);

        try
        {
            foreach (string command in this.ReadQuerys(this.FileSql))
                Console.WriteLine(command);
        }
        catch (ApplicationException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw new ApplicationException(string.Format("an unexpected error happened: {0}. ", ex.Message));
        }

    }

        private void RunMySQLCommand(string command)
        {
            try
            {
                using (MySqlCommand c = new MySqlCommand(command, this.MyConnection))
                {
                    c.ExecuteReader();
                    this.CorrectQuerys.Add(command);
                }
            }
            catch (Exception ex)
            {
                this.ErrorQuery = command;
                throw new ApplicationException(string.Format("error: {0}. command: {1}", ex.Message, command));
            }
        }

        private IEnumerable<string> ReadQuerys(string file)
        {
            using (StreamReader sr = new StreamReader(file)) 
            {
                string query = string.Empty;
                while (sr.Peek() >= 0)
                {
                    query += (char)sr.Read();
                    if (query.EndsWith(";"))
                    {
                        yield return query;
                        query = string.Empty;
                    }
                }
            }
        }

    }
}

try this for check error:

List<string> query = new List<string>(){
        "SET SQL_MODE= 'NO_AUTO_VALUE_ON_ZERO';",
        string.Format("CREATE DATABASE `{0}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;", dbName),
        string.Format("USE `{0}`;", dbName)}; // error string.Format("USE `{0}`;{1}", dbName)
/*    
using (StreamReader reader = File.OpenText("C:\b.sql"))
{
    while (reader.Peek() >= 0)
        query.Add(reader.ReadLine());
}
*/

using (StreamReader reader = File.OpenText("C:\b.sql"))
{
    string lines = reader.ReadToEnd();
    string[] alines = lines.Split(';');
    foreach(string q in alines) 
            query.Add(q);
}

foreach (string command in query)
{
    try
    {
        using (MySqlCommand c = new MySqlCommand(command, conn))
        {
            c.ExecuteReader();
            Console.WriteLine(string.Format("OK Command: {0}", command));
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(string.Format("Error: {0}. Command: {1}", ex.Message, command));
        break;
    }
}

Edit

for better performance, you can use this class. I have not tried it, hope it works well:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.IO;

namespace MySQLHelperTest
{
    public class MySQLTestingQuery
    {
        public MySqlConnection MyConnection { get; set; }
        public string FileSql { get; set; }
        public List<string> PreviousQuerys { get; set; }
        public List<string> CorrectQuerys { get; private set; }
        public string ErrorQuery { get; private set; }

        public MySQLTestingQuery()
        {
            this.CorrectQuerys = new List<string>();
            this.ErrorQuery = string.Empty;
        }

    public void Start()
    {
        FileInfo file = new FileInfo(this.FileSql);
        if (!file.Exists)
            throw new ApplicationException(string.Format("nonexistent file: '{0}'", this.FileSql));

        if (this.PreviousQuerys != null)
            foreach (string command in this.PreviousQuerys)
                this.RunMySQLCommand(command);

        try
        {
            foreach (string command in this.ReadQuerys(this.FileSql))
                Console.WriteLine(command);
        }
        catch (ApplicationException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw new ApplicationException(string.Format("an unexpected error happened: {0}. ", ex.Message));
        }

    }

        private void RunMySQLCommand(string command)
        {
            try
            {
                using (MySqlCommand c = new MySqlCommand(command, this.MyConnection))
                {
                    c.ExecuteReader();
                    this.CorrectQuerys.Add(command);
                }
            }
            catch (Exception ex)
            {
                this.ErrorQuery = command;
                throw new ApplicationException(string.Format("error: {0}. command: {1}", ex.Message, command));
            }
        }

        private IEnumerable<string> ReadQuerys(string file)
        {
            using (StreamReader sr = new StreamReader(file)) 
            {
                string query = string.Empty;
                while (sr.Peek() >= 0)
                {
                    query += (char)sr.Read();
                    if (query.EndsWith(";"))
                    {
                        yield return query;
                        query = string.Empty;
                    }
                }
            }
        }

    }
}
深海里的那抹蓝 2024-12-06 06:53:54

我不确定 MySql 的查询字符串的长度是否有限制。我的第一个想法是将庞大的 1700 行查询集分解为单独的查询。

string query = @"SET SQL_MODE= 'NO_AUTO_VALUE_ON_ZERO'; CREATE DATABASE " + dbName + " DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci" + Environment.NewLine;
MySqlCommand c;
c = new MySqlCommand(query, conn);
c.ExecuteNonQuery();

using (StreamReader reader = File.OpenText("C:\b.sql"))
{
    string line = reader.ReadToEnd();
    query = "USE " + dbName + "; " + line;
    c = new MySqlCommand(query, conn);
    c.ExecuteNonQuery();
}

这样您就可以创建数据库,然后单独运行每个查询。在不了解您的数据的情况下,这可能会帮助您查明任何问题。如果您用 try catch 块包围“ExecuteNonQuery”,您可以捕获任何失败的查询并将它们放入日志文件中以查看批处理何时完成。

I'm not sure if there is a limit to the length of a query string for MySql. My first thought would be to break the giant 1700 line set of queries into individual queries.

string query = @"SET SQL_MODE= 'NO_AUTO_VALUE_ON_ZERO'; CREATE DATABASE " + dbName + " DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci" + Environment.NewLine;
MySqlCommand c;
c = new MySqlCommand(query, conn);
c.ExecuteNonQuery();

using (StreamReader reader = File.OpenText("C:\b.sql"))
{
    string line = reader.ReadToEnd();
    query = "USE " + dbName + "; " + line;
    c = new MySqlCommand(query, conn);
    c.ExecuteNonQuery();
}

This way you could create the database and then run each query individually. Without knowing your data this may help you pinpoint any issues. If you surrounded the "ExecuteNonQuery" with a try catch block you could catch any queries that fail and put them in a log file to look at when the batch is done.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文