c#连接SqlServer2000
aspx文件中代码如下:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 id="Head1" runat="server">
<title>c# conn sqlserver</title>
</head>
<body>
<form id="form" runat="server">
<div>
<asp:GridView ID="EmpGridView" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
aspx对应的cs文件代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string ConnectString =
@"server=localhost;uid=root;pwd=root;database=Northwind";
SqlConnection conn = new SqlConnection(ConnectString);
SqlDataAdapter adapter = null;
DataSet ds = null;
try
{
conn.Open();
adapter = new SqlDataAdapter(
"SELECT FirstName,LastName,City FROM Employees", conn);
ds = new DataSet();
adapter.Fill(ds);
EmpGridView.DataSource = ds.Tables[0].DefaultView;
EmpGridView.DataBind();
}
finally
{
conn.Close();
}
}
}
c#连接Access 2007
aspx文件中代码如下:
<%@ Page Language="C#" AutoEventWireup="true" Debug="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 id="Head1" runat="server">
<title>c# conn access2007</title>
</head>
<body>
<form id="form" runat="server">
<div>
<asp:Button ID="btnConnetDatabase" runat="server" Height="27px"
.Click="btnConnetDatabase_Click"
Text="c# conn access2007" Width="108px" /><br />
<asp:GridView ID="EmpGridView" runat="server" Width="245px">
</asp:GridView>
</div>
</form>
</body>
</html>
aspx对应的cs文件代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
protected void btnConnetDatabase_Click(object sender, EventArgs e)
{
string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"] + "Database1.accdb";
OleDbConnection conn = new OleDbConnection(ConnectionString);
conn.Open();
OleDbDataAdapter adaptor = new OleDbDataAdapter(
"SELECT * FROM Type", conn);
DataSet empdataset = new DataSet();
try
{
adaptor.Fill(empdataset);
EmpGridView.DataSource = empdataset.Tables[0].DefaultView;
EmpGridView.DataBind();
}
catch (Exception err)
{
}
finally
{
conn.Close();
}
}
}
注:要将.accdb文件放入于aspx同级的目录中