使用asp.net c#下载SQL server表的内容

本文关键字:server SQL asp net 下载 使用 | 更新日期: 2023-09-27 18:07:32

 // I want to use the SQL Query SELECT * FROM Table here, how can I do that?      
string filepath = Server.MapPath("test.doc");
 FileInfo file = new FileInfo(filepath);
 // Checking if file exists
 if (file.Exists)
 {
// Clear the content of the response
Response.ClearContent();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
// Add the file size into the response header
Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
Response.ContentType = ReturnExtension(file.Extension.ToLower());
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
Response.TransmitFile(file.FullName);
// End the response
Response.End();
}

谁能帮助我得到表的内容称为表在SQL Server 2008和下载它?我有上面的代码,但目前它从路径读取,如何使它从SELECT查询读取?这里的查询是"SELECT* FROM Table"

使用asp.net c#下载SQL server表的内容

一种方法是使用SQLDataReader(我不打算在这里解释连接等:我假设您以前调用过数据库)并手动连接列

您通常使用bcp.exe或SMO。

您可以使用SqlDataAdapter来获取数据并根据数据填充数据表:

        SqlConnection connection = new SqlConnection(connectionString);
        string query = "SELECT * FROM Table";
        SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
        connection.Open();
        DataTable table = new DataTable();
        try
        {
            adapter.Fill(table);           
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            connection.Close();           
        }
    }