ASP.net C#鏈接SQLserver數據庫 VS2012

第一步:打開VS2012,新建—>項目—>其它項目類型—>VS解決方案;右擊添加—>新建項目—>選擇C# Web—>ASP.Net空Web程序(本文)或ASP.NetWeb窗體程序sql

第二步:向新建的Web程序中右擊添加Web窗體至此項目新建完成數據庫

第三步:雙擊Web.config添加以下代碼:服務器

<connectionStrings>
<add name="myConn" connectionString ="Data Source=(10.100.61.13)\v11.0;Database=DataName;uid=用戶名;pwd=密碼;AttachDbFilename=|DataDirectory| \Movies.mdf;Integrated Security=True" providerName ="System.Data.SqlClient" />
</connectionStrings>ide

注:Data Source爲數據庫服務器名(地址);Database:數據庫名;函數

第四步:鏈接數據庫。在aspx.cs文件中添加以下代碼:ui

protected void Page_Load(object sender, EventArgs e)
{
string strconn = "server=10.100.61.13;Database=DataName;uid=sa;pwd=密碼";
SqlConnection conn = new SqlConnection(strconn); //建立鏈接
string sql = "select * from TS_Menu";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn); //執行查詢
Response.Write("鏈接成功");
SqlDataReader dr = cmd.ExecuteReader(); //查詢結果
customers.DataSource=dr;
customers.DataBind();
dr.Close();
conn.Close();this

// this.Lab.Text = "suc";
}spa

注:必定要在.cs中添加這樣不可以在網頁審查元素時看到數據庫的地址,添加using System.Web.UI.WebControls;server

另外也能夠創建一個函數形式的鏈接方式cmd

private DataSet Conn(string text,CommandType type)
{
DataSet ds=new DataSet();
string strconn = "server=10.100.61.13;Database=DataName;uid=sa;pwd=密碼";
using (SqlConnection conn = new SqlConnection(strconn))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
}
return ds;
}

第五步:在網頁中顯示數據。在.aspx文件中添加要先睡的數據代碼以下:

<asp:Repeater id="customers" runat="server">

<HeaderTemplate>
<table style="border:1px solid #ff6a00;width:100%">
<tr style="background-color:#00ffff">
<th>MenuID</th>
<th>MenuName</th>
<th>ParentID</th>
<th>MenuNote</th>
<th>MenuUrl</th>
<th>Controller</th>
<th>Action</th>
<th>OrderNum</th>
<th>NeedCheck</th>
<th>Visiable</th>
<th>IsMenu</th>
</tr>
</HeaderTemplate>

<ItemTemplate>
<tr style="background-color:#6bbdf7">
<td><%#Eval("MenuID")%> </td>
<td><%#Eval("MenuName")%> </td>
<td><%#Eval("ParentID")%> </td>
<td><%#Eval("MenuNote")%> </td>
<td><%#Eval("MenuUrl")%> </td>
<td><%#Eval("Controller")%> </td>
<td><%#Eval("Action")%> </td>
<td><%#Eval("OrderNum")%> </td>
<td><%#Eval("NeedCheck")%> </td>
<td><%#Eval("Visiable")%> </td>
<td><%#Eval("IsMenu")%> </td>
</tr>
</ItemTemplate>

<FooterTemplate>
</table>
</FooterTemplate>

</asp:Repeater>

注:輸出是要Eval具體我也不清楚網上查的,還要導入

<%@ Import Namespace="System.Data.SqlClient" %><%@ Import Namespace="System.Data" %>兩個包

相關文章
相關標籤/搜索