0

テーブル名を抽出して変数に保存したいのですが、これは学生、教師、スコアの 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

4 に答える 4

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);
于 2012-12-06T10:50:42.827 に答える
0

将来のユーザーまたは別のセッションのために結果を保存する場合は、次のいずれかのメソッドを使用できます

最初に、「挿入」クエリを使用して、データを保存するために特別に作成する別のテーブルに結果を 1 つずつ保存します。挿入コマンド/ステートメントを for ループに直接配置できます。

2 番目の方法では、xml を使用して値を格納します。非常にシンプルでメモリにやさしい

于 2012-12-06T10:44:39.617 に答える
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();
  //...
  }
于 2012-12-06T10:42:45.123 に答える
0

ArrayList を使用してテーブル名の数を単一の変数に格納するように @Doctor コードを変更しました。

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());
    //...
}
于 2012-12-06T11:00:00.680 に答える