程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> 關於ASP.NET >> asp.net連接數據庫讀取數據示例分享

asp.net連接數據庫讀取數據示例分享

編輯:關於ASP.NET

     這篇文章主要介紹了asp.net連接數據庫讀取數據示例,大家參考使用吧

    webconfig配置:    代碼如下: <connectionStrings>   <add name="MSSQL" connectionString="Data Source=localhost;Initial Catalog=test;User ID=sa;password=sa;" providerName="System.Data.SqlClient"/> </connectionStrings>     前台aspx: 代碼如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DB.aspx.cs" Inherits="DB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title>DB</title> </head> <body>     <form id="form1" runat="server">     <div>             MS SQL<asp:GridView ID="GridView1" runat="server">         </asp:GridView>     </div>     </form> </body> </html>     後台代碼:    代碼如下: using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.Common;//記得要using using System.Configuration;   public partial class DB : System.Web.UI.Page {     protected void Page_Load(object sender, EventArgs e)     {         DataSet dsMSSQL = GetDataSet("select * from [Table]", "MSSQL");         this.GridView1.DataSource = dsMSSQL;         this.GridView1.DataBind();     }       protected DataSet GetDataSet(string SqlCommand,string DB)     {         DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings[DB].ProviderName);         DbConnection dbConnection = dbProviderFactory.CreateConnection();         dbConnection.ConnectionString = ConfigurationManager.ConnectionStrings[DB].ConnectionString;           DataSet ds = new DataSet();           DbCommand dbCommand = dbProviderFactory.CreateCommand();         dbCommand.Connection = dbConnection;         DbDataAdapter dbDataAdapter = dbProviderFactory.CreateDataAdapter();         dbCommand.CommandText = SqlCommand;         dbDataAdapter.SelectCommand = dbCommand;         dbDataAdapter.Fill(ds);           return ds;     } }  
    1. 上一頁:
    2. 下一頁:
    Copyright © 程式師世界 All Rights Reserved