ADO.NET 数据库示例

读取数据库

<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection connection = new SqlConnection();
        SqlCommand command;
        SqlDataReader datareader;
        connection.ConnectionString = "Server=mypc;Database=asteras;Trusted_Connection=true";
        connection.Open();
        command = connection.CreateCommand();
        command.CommandText = "select name from ast_users";
        datareader = command.ExecuteReader();
        while (datareader.Read())
        {
            DropDownList1.Items.Add( datareader.GetValue(0).ToString() );
        }
        datareader.Close();
        connection.Close();        
    }
</script>

<html>
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>&nbsp;</div>
    </form>
</body>
</html>