我的网站(远程)上有一个sql server表。该表名为table1
,包含一堆字段。我的目标是将table1
的所有字段读入名为results
的数组中。
这是我的尝试:
private static void ShowFields()
{
using (SqlConnection connection = new SqlConnection(connectionstring))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='table1'", connection);
string[] results = command.BeginExecuteNonQuery().ToArray();
connection.Close();
foreach (var v in results)
{
Console.WriteLine(v);
}
}
}
答案 0 :(得分:0)
你想要探索
SqlCommand.ExecuteReader
或用结果填充DataSet。
http://msdn.microsoft.com/en-us/library/bh8kx08z%28v=vs.71%29.aspx
BeginExecuteNonQuery是异步的,我会传递这个,直到你得到基础知识。
答案 1 :(得分:0)
您需要使用Sqlcoomand.Executereader()
代替:
private static void ShowFields()
{
using (SqlConnection connection = new SqlConnection(connectionstring))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='table1'", connection);
SqlDataReader reader = command.ExecuteReader();
connection.Close();
int colCount = reader.FieldCount;
while (reader.Read())
{
for (int i = 0; i < colCount; i++)
{
Console.WriteLine(reader.GetString(i));
}
}
}
}
答案 2 :(得分:0)
这是另一种方式:
System.Data.SqlClient.SqlCommand c = new System.Data.SqlClient.SqlCommand();
System.Data.DataTable T = new System.Data.DataTable();
System.Data.SqlClient.SqlDataAdapter DA = new System.Data.SqlClient.SqlDataAdapter(c);
c.commandtext = "select ..";
DA.SelectCommand = c;
c.Connection = new System.Data.SqlClient.SqlConnection(yourConnectionString);
c.Connection.Open();
DA.Fill(T);
// close connection in finally block or use the using structure
然后检查T.