C# 为什么函数会给出不需要的值

C# 为什么函数会给出不需要的值,c#,C#,我有一个类似这样的函数,用于在组合框中绑定所选数据库的主键: //An instance of the connection string is created to manage the contents of the connection string. var sqlConnection = new SqlConnectionStringBuilder(); sqlConnection.DataSource = "192.168.10.3"; sqlConnection.UserID =

我有一个类似这样的函数,用于在组合框中绑定所选数据库的主键:

//An instance of the connection string is created to manage the contents of the connection string.

var sqlConnection = new SqlConnectionStringBuilder();
sqlConnection.DataSource = "192.168.10.3";
sqlConnection.UserID = "gp";
sqlConnection.Password = "gp";
sqlConnection.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue);
string connectionString = sqlConnection.ConnectionString;

SqlConnection sConnection = new SqlConnection(connectionString);

//To Open the connection.
sConnection.Open();

//Query to select the table_names that have PRIMARY_KEYS.
string selectPrimaryKeys = @"SELECT TABLE_NAME 
                             FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                             WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
                             ORDER BY TABLE_NAME";

//Create the command object
SqlCommand sCommand = new SqlCommand(selectPrimaryKeys, sConnection);

try
{
    //Create the dataset
    DataSet dsListOfPrimaryKeys = new DataSet("INFORMATION_SCHEMA.TABLE_CONSTRAINTS");

    //Create the dataadapter object
    SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeys, sConnection);

    //Provides the master mapping between the sourcr table and system.data.datatable
    sDataAdapter.TableMappings.Add("Table", "INFORMATION_SCHEMA.TABLE_CONSTRAINTS");

    //Fill the dataset
    sDataAdapter.Fill(dsListOfPrimaryKeys);

    //Bind the result combobox with primary key tables
    DataViewManager dvmListOfPrimaryKeys = dsListOfPrimaryKeys.DefaultViewManager;
    cmbResults.DataSource = dsListOfPrimaryKeys.Tables["INFORMATION_SCHEMA.TABLE_CONSTRAINTS"];
    cmbResults.DisplayMember = "TABLE_NAME";
    cmbResults.ValueMember = "TABLE_NAME";
}
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);
}
finally
{
    //If connection is not closed then close the connection
    if(sConnection.State != ConnectionState.Closed)
    {
        sConnection.Close();
}

但是它会产生一个不需要的结果,比如dtproperties。查询有什么问题吗?

虽然主键在技术上是表的一部分,而不是数据库,但假设您的查询是正确的,请在您的C代码中尝试这一点。它有一些内存和性能上的改进,同时还能捕获连接异常

public void GetPrimaryKeyTable() {
    //An instance of the connection string is created to manage the contents of the connection string.

    var sqlConnection = new SqlConnectionStringBuilder();
    sqlConnection.DataSource = "192.168.10.3";
    sqlConnection.UserID = "gp";
    sqlConnection.Password = "gp";
    sqlConnection.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue);

    // Automatically close the connection
    using(SqlConnection sConnection = new SqlConnection(sqlConnection.ConnectionString)) {
        try {
            sConnection.Open();

            //Query to select the table_names that have PRIMARY_KEYS.
            string selectPrimaryKeys = @"SELECT TABLE_NAME 
                                        FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                                        WHERE   CONSTRAINT_TYPE = 'PRIMARY KEY'
                                        ORDER   BY TABLE_NAME";

            //Create the command object
            using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeys, sConnection)) {
                // Bind the combobox without destroying the data reader object after binding (no using statement)
                cmbResults.DisplayMember = "TABLE_NAME";
                cmbResults.ValueMember = "TABLE_NAME";  
                cmbResults.DataSource sReader = sCommand.ExecuteReader();
                cmbResults.DataBind();
            }
        }
        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);
        }
        finally {
            // Read somewhere that the using statement takes care of this for you
            // but just in case
            if(sConnection.State != ConnectionState.Closed) {
                sConnection.Close();
            }
        }
    }
}
至于查询,在SQLServer2008R2中,它返回一个具有主键的表列表。列表中的每个表都是具有主键的表。您使用的是什么版本的SQL Server

编辑:如果希望查询仅返回用户表并过滤掉系统表之类的内容,请尝试以下查询:

SELECT  tc.TABLE_NAME 
FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER   JOIN sysobjects so
        ON tc.TABLE_NAME = so.name
WHERE   tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
        AND so.xtype = 'U'
ORDER   BY TABLE_NAME;

虽然主键在技术上是表的一部分,而不是数据库的一部分,但假设您的查询是正确的,请在您的C代码中尝试此方法。它有一些内存和性能上的改进,同时还能捕获连接异常

public void GetPrimaryKeyTable() {
    //An instance of the connection string is created to manage the contents of the connection string.

    var sqlConnection = new SqlConnectionStringBuilder();
    sqlConnection.DataSource = "192.168.10.3";
    sqlConnection.UserID = "gp";
    sqlConnection.Password = "gp";
    sqlConnection.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue);

    // Automatically close the connection
    using(SqlConnection sConnection = new SqlConnection(sqlConnection.ConnectionString)) {
        try {
            sConnection.Open();

            //Query to select the table_names that have PRIMARY_KEYS.
            string selectPrimaryKeys = @"SELECT TABLE_NAME 
                                        FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                                        WHERE   CONSTRAINT_TYPE = 'PRIMARY KEY'
                                        ORDER   BY TABLE_NAME";

            //Create the command object
            using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeys, sConnection)) {
                // Bind the combobox without destroying the data reader object after binding (no using statement)
                cmbResults.DisplayMember = "TABLE_NAME";
                cmbResults.ValueMember = "TABLE_NAME";  
                cmbResults.DataSource sReader = sCommand.ExecuteReader();
                cmbResults.DataBind();
            }
        }
        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);
        }
        finally {
            // Read somewhere that the using statement takes care of this for you
            // but just in case
            if(sConnection.State != ConnectionState.Closed) {
                sConnection.Close();
            }
        }
    }
}
至于查询,在SQLServer2008R2中,它返回一个具有主键的表列表。列表中的每个表都是具有主键的表。您使用的是什么版本的SQL Server

编辑:如果希望查询仅返回用户表并过滤掉系统表之类的内容,请尝试以下查询:

SELECT  tc.TABLE_NAME 
FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER   JOIN sysobjects so
        ON tc.TABLE_NAME = so.name
WHERE   tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
        AND so.xtype = 'U'
ORDER   BY TABLE_NAME;
dtproperties是SQLServer用来存储关系图信息的表。在某些版本的SQL Server中,它被标记为用户表而不是系统表,因此将由查找用户表的查询返回

也许只是用这样的东西过滤掉它:

string selectPrimaryKeys = @"SELECT 
                                       TABLE_NAME 
                                   FROM
                                       INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                                  WHERE 
                                       CONSTRAINT_TYPE = 'PRIMARY KEY'
                                       AND TABLE_NAME <> 'dtproperties'
                               ORDER BY 
                                       TABLE_NAME";
dtproperties是SQLServer用来存储关系图信息的表。在某些版本的SQL Server中,它被标记为用户表而不是系统表,因此将由查找用户表的查询返回

也许只是用这样的东西过滤掉它:

string selectPrimaryKeys = @"SELECT 
                                       TABLE_NAME 
                                   FROM
                                       INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                                  WHERE 
                                       CONSTRAINT_TYPE = 'PRIMARY KEY'
                                       AND TABLE_NAME <> 'dtproperties'
                               ORDER BY 
                                       TABLE_NAME";

预期输出和当前输出是什么?我们需要更多的细节。您是否尝试过使用类似SQL Management Studio的工具直接对数据库运行查询?是的,在查询中存在问题…它在SQL Management Studio中显示相同的结果。嘿,您的SQL连接在方法末尾未被释放!因此,您的问题是,您得到了一个表列表,但列表中出现了“dtproperties”,您不知道为什么?预期输出是什么,当前输出是什么?我们需要更多的细节。您是否尝试过使用类似SQL Management Studio的工具直接对数据库运行查询?是的,在查询中存在问题…它在SQL Management Studio中显示相同的结果。嘿,您的SQL连接在方法末尾未被释放!因此,您的问题是,您得到了一个表列表,但列表中出现了“dtproperties”,您不知道为什么?我的错误是,方法名称是ExecuteReader not ExecuteDataReader。我更新了答案以反映这一点。我的错误是,方法名称为ExecuteReader not ExecuteDataReader。我更新了我的答案以反映这一点。