ASP.NET连接SQL Server数据库

 <%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
 <head>
 <title>test sql server connection</title>
 </head>
 <body>
 <h4>first example:listing data from a SQLServer table</h4>
 <asp:DataGrid id="dgUserList"
 runat="server"
 GridLines="None"
 BackColor="LightBlue"
 CellPadding="5"
 CellSpacing="5"
 BorderWidth="2"
 BorderColor="Black"
 ToolTip="Show all the userinfo"/>
 </body>
</html>
<script language="C#" runat="server">
private void Page_Load(Object sender, EventArgs e) {
   String strConnection="server=(local);database=users;uid=test;pwd=test;";
   SqlConnection objConnection=new SqlConnection(strConnection);
   String strSQL="SELECT * FROM userinfo";
   SqlCommand objCommand=new SqlCommand(strSQL,objConnection);
  
   objConnection.Open();
   dgUserList.DataSource=objCommand.ExecuteReader();
   dgUserList.DataBind();
   objConnection.Close();
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET 中,连接 SQL Server 数据库有多种方式。以下是其中两种常见的方法: 1. 使用 SqlConnection 和 SqlCommand 对象连接和执行 SQL 命令 ``` using System.Data.SqlClient; string connectionString = "Data Source=YourServerName;Initial Catalog=YourDatabaseName;User ID=YourUsername;Password=YourPassword"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "SELECT * FROM YourTableName"; using (SqlCommand command = new SqlCommand(sql, connection)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string column1 = reader["ColumnName1"].ToString(); string column2 = reader["ColumnName2"].ToString(); // ... } } } } ``` 2. 使用 Entity Framework 连接和操作数据 首先需要安装 Entity Framework NuGet 包。然后可以通过创建 DbContext 类和 Entity 类来定义数据模型和连接字符串,然后通过 DbContext 实例来执行数据库操作。 ``` using System.Data.Entity; public class MyDbContext : DbContext { public MyDbContext() : base("name=MyConnectionString") { } public DbSet<MyEntity> MyEntities { get; set; } } public class MyEntity { public int Id { get; set; } public string Column1 { get; set; } public string Column2 { get; set; } // ... } using (MyDbContext context = new MyDbContext()) { var results = context.MyEntities.ToList(); foreach (var result in results) { string column1 = result.Column1; string column2 = result.Column2; // ... } } ``` 以上是两种常见的连接 SQL Server 数据库的方法,具体使用哪种取决于你的需求和偏好。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值