存储选择结果

时间:2012-12-06 10:32:40

标签: c#

我想提取我的表名并将其保存到变量中这是我的鳕鱼,它返回3个答案:学生,老师和分数。如何更改它以将这些树表名保存为3变量。谢谢。

try
{
  SqlDataReader myreader = null;
  SqlCommand mycommand = new SqlCommand("select * FROM information_schema.tables WHERE table_type = 'BASE TABLE'", myconnect);
  myreader = mycommand.ExecuteReader();
  while (myreader.Read())
  {
    Console.WriteLine(myreader[2].ToString());
  }
}

4 个答案:

答案 0 :(得分:1)

一种简单的内置方法是使用Connection.GetSchema

using (var con = new System.Data.SqlClient.SqlConnection(conStr))
{
    con.Open();
    DataTable schemaTable = con.GetSchema("Tables");
    IList<string> allTableNames = schemaTable.AsEnumerable()
        .Where(r => r.Field<string>("TABLE_TYPE") == "BASE TABLE")
        .Select(r => r.Field<string>("TABLE_NAME"))
        .ToList();
}

现在您有一个List<string>,其中包含您可以通过索引器或循环访问的所有表名,或者使用string.Join创建逗号分隔列表:

string tNames = string.Join(",", allTableNames);
Console.Write("all tables in the given database: " + tNames);

答案 1 :(得分:0)

您可以使用:

string tableName ="" ; // Variable to stroe the table names
string connectionString = ""; //Your connectionstring
// get records from the table
string commandString =""; //Your query
// create the data set command object
// and the DataSet
SqlDataAdapter DataAdapter =new SqlDataAdapter(commandString, connectionString);
DataSet DataSet = new DataSet( );

// fill the DataSet object
DataAdapter.Fill(DataSet, "Customers");
// Get the one table from the DataSet
DataTable dataTable = DataSet.Tables[0];
// for each row in the table, display the info
foreach (DataRow dataRow in dataTable.Rows)
 {

  tableName = dataRow[0].tostring();
  //...
  }

答案 2 :(得分:0)

如果您想为将来的用户或其他会话保存结果,那么您可以使用以下任何方法

第一个 使用“插入”查询将结果逐个保存在您专门为保存数据而创建的另一个表中 你可以将insert命令/语句直接放入for循环

第二种方法 使用xml来存储非常简单且内存友好的值

答案 3 :(得分:0)

我修改了@Doctor代码以使用ArrayList在单个变量中存储表名的数量。

ArrayList alTableName  = new ArrayList(); // Variable to stroe the table names
string connectionString = ""; //Your connectionstring
// get records from the table
string commandString =""; //Your query
// create the data set command object
// and the DataSet

SqlDataAdapter DataAdapter =new SqlDataAdapter(commandString, connectionString);
DataSet DataSet = new DataSet( );

// fill the DataSet object
DataAdapter.Fill(DataSet, "Customers");

// Get the one table from the DataSet
DataTable dataTable = DataSet.Tables[0];

// for each row in the table, display the info
foreach (DataRow dataRow in dataTable.Rows)
{

    alTableName.Add(dataRow[0].tostring());
    //...
}