需要将DataTable返回类型转换为字符串

发布于 2024-10-06 06:24:15 字数 2494 浏览 0 评论 0原文

我有一个函数可以返回数据表中具有主键的表列表,但现在需要获取字符串返回类型中的表列表。

我的方法如下:

public DataTable GetAllPrimaryKeyTables 
   (string localServer, string userName, string password, string selectedDatabase)
{

    // Create the datatable 
    DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");

    SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder();
    objConnectionString.DataSource = localServer; ;
    objConnectionString.UserID = userName;
    objConnectionString.Password = password;
    objConnectionString.InitialCatalog = selectedDatabase;

    // Query to select primary key tables.
    string selectPrimaryKeyTables = @"SELECT 
                                           TABLE_NAME
                                          AS
                                           TABLES
                                        FROM 
                                           INFORMATION_SCHEMA.TABLE_CONSTRAINTS
                                       WHERE 
                                           CONSTRAINT_TYPE = 'PRIMARY KEY'
                                    ORDER BY
                                           TABLE_NAME";

    // put your SqlConnection and SqlCommand into using blocks! 
    using(SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString))
    using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
    {
        try
        {
            // Create the dataadapter object 
            SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);

            // Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself  
            // (and also close it again after it is done) 
            sDataAdapter.Fill(dtListOfPrimaryKeyTables);

        }
        catch(Exception ex)
        {
            //All the exceptions are handled and written in the EventLog. 
            EventLog log = new EventLog("Application");
            log.Source = "MFDBAnalyser";
            log.WriteEntry(ex.Message);
        }
    }

    // return the data table to the caller 
    return dtListOfPrimaryKeyTables;
}

但是现在我想在下面的函数中调用这个逻辑...我已经尝试过但没有完成。

public class PrimaryKeyChecker : IMFDBAnalyserPlugin
{
    public string RunAnalysis(string ConnectionString)
    {
        return "string";
    }
}

我需要将函数的返回类型调整为字符串类型,并将整个逻辑包含在 RunAnalysis 方法中,

请你们帮助我!

I have a function to return the list of tables having primary key in a datatable, but now the need is to get the table list in the string return type.

My method is as follows:

public DataTable GetAllPrimaryKeyTables 
   (string localServer, string userName, string password, string selectedDatabase)
{

    // Create the datatable 
    DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");

    SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder();
    objConnectionString.DataSource = localServer; ;
    objConnectionString.UserID = userName;
    objConnectionString.Password = password;
    objConnectionString.InitialCatalog = selectedDatabase;

    // Query to select primary key tables.
    string selectPrimaryKeyTables = @"SELECT 
                                           TABLE_NAME
                                          AS
                                           TABLES
                                        FROM 
                                           INFORMATION_SCHEMA.TABLE_CONSTRAINTS
                                       WHERE 
                                           CONSTRAINT_TYPE = 'PRIMARY KEY'
                                    ORDER BY
                                           TABLE_NAME";

    // put your SqlConnection and SqlCommand into using blocks! 
    using(SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString))
    using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
    {
        try
        {
            // Create the dataadapter object 
            SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);

            // Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself  
            // (and also close it again after it is done) 
            sDataAdapter.Fill(dtListOfPrimaryKeyTables);

        }
        catch(Exception ex)
        {
            //All the exceptions are handled and written in the EventLog. 
            EventLog log = new EventLog("Application");
            log.Source = "MFDBAnalyser";
            log.WriteEntry(ex.Message);
        }
    }

    // return the data table to the caller 
    return dtListOfPrimaryKeyTables;
}

But now I want this logic to be called in the function below...I have tried but it is not done.

public class PrimaryKeyChecker : IMFDBAnalyserPlugin
{
    public string RunAnalysis(string ConnectionString)
    {
        return "string";
    }
}

I need to adjust the returntype of the function to string type and the whole logic to be covered in the RunAnalysis method

Would you guys please help me!!!

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

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

发布评论

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

评论(4

三生池水覆流年 2024-10-13 06:24:15

要将 DataTable 转换为字符串,您可以使用 DataTable 的功能将其自身写入 Xml,然后将 Xml 转换为字符串。

To convert a DataTable to a string, you can use the DataTable's ability to write itself to Xml, and then convert the Xml to a string.

十级心震 2024-10-13 06:24:15
return (from rowItem in dt.AsEnumerable()
               select Convert.ToString(rowItem["TABLES"])).ToList();

编辑:将表名称作为 IList 集合返回。

return (from rowItem in dt.AsEnumerable()
               select Convert.ToString(rowItem["TABLES"])).ToList();

Edit: returns your table names as an IList collection.

时光病人 2024-10-13 06:24:15

不确定我 100% 理解你的问题,但看来你需要做的就是:

  1. 运行你得到的代码,并将其转换为字符串
  2. 将代码重构为数据读取器,然后直接将其传回,省略使用数据集/数据表。

要调整 PrimaryKeyChecker 代码并返回一串表,您可以编写如下内容:

public string RunAnalysis(string localServer, string userName, string password, string selectedDatabase)
{
    DataTable dt = GetAllPrimaryKeyTables(localServer, userName, password, selectedDatabase);
    StringBuilder sb = new StringBuilder();
    foreach (DataRow dr in dt.Rows)
    {
        sb.AppendLine(dr.IsNull(0) ? "" : dr[0].ToString());
    }
    return sb.ToString();
}

但是我建议至少返回一个列表,以便可以轻松搜索和过滤它并用于在 UI 上呈现。

如果我完全误解了你的问题,我深表歉意。

Not sure I 100% understand your question, but it appears that all you need to do is either:

  1. Run the code you've got, and convert it into a string
  2. Refactor the code into datareaders and just pass it back directly, omitting the use of DataSets/DataTables.

To adapt your PrimaryKeyChecker code and return a string of tables, you could write something like this:

public string RunAnalysis(string localServer, string userName, string password, string selectedDatabase)
{
    DataTable dt = GetAllPrimaryKeyTables(localServer, userName, password, selectedDatabase);
    StringBuilder sb = new StringBuilder();
    foreach (DataRow dr in dt.Rows)
    {
        sb.AppendLine(dr.IsNull(0) ? "" : dr[0].ToString());
    }
    return sb.ToString();
}

However I would recommend at the very least, returning a List so it can be easily searched and filtered and used for presentation on the UI.

I apologise if I've completely misunderstood your question.

一个人的夜不怕黑 2024-10-13 06:24:15
using System.Linq;
...

public string GetAllPrimaryKeyTableNames(string localServer, string userName, string password, string selectedDatabase) {
    DataTable table = GetAllPrimaryKeyTables(localServer, userName, password, selectedDatabase);

    return string.Join(",", table.AsEnumerable().Select(r => r.ItemArray[0]).ToArray());
}

这将返回一个字符串,其中包含用逗号分隔的表名称。

编辑

我在你的问题中看到你的方法名为 RunAnalysis。请随意将我的答案中的方法名称以及参数更改为您需要的任何名称。重要的部分是 LINQ 中的 string.Join 用法。

using System.Linq;
...

public string GetAllPrimaryKeyTableNames(string localServer, string userName, string password, string selectedDatabase) {
    DataTable table = GetAllPrimaryKeyTables(localServer, userName, password, selectedDatabase);

    return string.Join(",", table.AsEnumerable().Select(r => r.ItemArray[0]).ToArray());
}

This will return a string containing your table names separated by a comma.

EDIT

I see in your question you have your method named RunAnalysis. Feel free to change the method name in my answer to whatever you need it to be, as well as the parameters. The important part is the string.Join usage with LINQ.

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