【发布时间】:2017-10-16 10:58:41
【问题描述】:
我正在尝试使用此代码,但它给了我错误,我只想使用数据表而不是数据集
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public DataTable NameArray()
{
DataTable imageTable = new DataTable("gcm");
// imageTable.Columns.Add("image_name", typeof(String));
imageTable.Columns.Add("username", typeof(String));
imageTable.Columns.Add("gcmkey", typeof(String));
if (con.State.ToString() == "Closed")
{
con.Open();
}
string query = "SELECT * from gcm";
SqlCommand command = new SqlCommand(query, con);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
imageTable.Rows.Add(reader["username"],reader["gcmkey"]);
}
}
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(json.Serialize(new { PersonalProfile = reader }));
reader.Close();
con.Close();
return imageTable; }
错误显示如下:
This page contains the following errors:
error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.
那么,如何从数据表中获取数据,而不是从数据集中获取数据?
【问题讨论】:
-
为什么不用使用SQlDataAdapter来填充数据表而不是SqlDataReader呢?填写数据表是一条指令。代码看起来应该可以工作。所以要么阅读器代码有错误,要么查询没有返回任何行。这是您收到文档为空的错误消息的唯一两个原因。