我有一个函数来返回在数据表中具有主键的表的列表,但现在需要在字符串返回类型中获取表列表。
我的方法如下:
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方法中涵盖的整个逻辑
请你们帮帮我!!!
答案 0 :(得分:0)
要将DataTable转换为字符串,您可以使用DataTable将自身写入Xml的能力,然后将Xml转换为字符串。
答案 1 :(得分:0)
return (from rowItem in dt.AsEnumerable()
select Convert.ToString(rowItem["TABLES"])).ToList();
编辑:将您的表名称作为IList集合返回。
答案 2 :(得分:0)
不确定我是否100%理解您的问题,但似乎您需要做的只是:
要调整您的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();
}
但是我建议至少返回一个List,以便可以轻松搜索和过滤,并用于在UI上进行演示。
如果我完全误解了你的问题,我道歉。
答案 3 :(得分:0)
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。随意更改我的答案中的方法名称,无论你需要什么,以及参数。重要的部分是string.Join与LINQ的使用。