连接当前目录的一个Access数据库看文件,利用Connection对象打开一个数据库连接,然后利用State属性将状态显示到浏览器上。
using System.Data.OleDb;
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("person.mdb");
conn.Open();
Message.Text = conn.State.ToString();
conn.Close();
}
<form id="form1" runat="server">
<div>
<asp:Label ID="Message" runat="server" Width="288px"></asp:Label> </div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("person.mdb");
conn.Open();
Message.Text = conn.State.ToString();
conn.Close();
}
<form id="form1" runat="server">
<div>
<asp:Label ID="Message" runat="server" Width="288px"></asp:Label> </div>
</form>
方法二:
可以通过Connection对象的构造函数传入连接串
using System.Data.OleDb;
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("person.mdb"));
conn.Open();
Message.Text = conn.State.ToString();
conn.Close();
}
<form id="form1" runat="server">
<div>
<asp:Label ID="Message" runat="server" Width="288px"></asp:Label> </div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("person.mdb"));
conn.Open();
Message.Text = conn.State.ToString();
conn.Close();
}
<form id="form1" runat="server">
<div>
<asp:Label ID="Message" runat="server" Width="288px"></asp:Label> </div>
</form>
方法三:
连接SQL Server数据库,只需修改命名空间
using System.Data.SqlClient;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=localhost;database=pubs;uid=sa;pwd=''";
conn.Open();
Message.Text = conn.State.ToString();
conn.Close();
}
<form id="form1" runat="server">
<div>
<asp:Label ID="Message" runat="server" Width="288px"></asp:Label> </div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=localhost;database=pubs;uid=sa;pwd=''";
conn.Open();
Message.Text = conn.State.ToString();
conn.Close();
}
<form id="form1" runat="server">
<div>
<asp:Label ID="Message" runat="server" Width="288px"></asp:Label> </div>
</form>