在ASP.NET中,操作数据库表是一个常见的任务,包括创建、读取、更新和删除数据,以下是关于如何在ASP.NET中使用C#语言与数据库进行交互的详细内容:

一、数据库连接
1、连接字符串:
在ASP.NET中,首先需要定义一个连接字符串来指定要连接的数据库,对于SQL Server数据库,连接字符串可能如下所示:
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
2、SqlConnection对象:
使用SqlConnection类来建立与数据库的连接。
SqlConnection conn = new SqlConnection(connectionString);
3、打开连接:
在执行数据库操作之前,需要打开连接。
conn.Open();
二、创建数据表
1、使用SQL语句创建表:
可以通过执行SQL语句来创建新的数据表,以下是一个创建名为Students的数据表的例子:
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
EnrollmentDate DATETIME
);
在C#代码中执行这个SQL语句:
string createTableQuery = @"CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
EnrollmentDate DATETIME
)";
SqlCommand command = new SqlCommand(createTableQuery, conn);
command.ExecuteNonQuery();
三、插入数据
1、使用SqlCommand插入数据:
使用SqlCommand对象执行INSERT语句向表中添加数据。

string insertQuery = "INSERT INTO Students (StudentID, FirstName, LastName, EnrollmentDate) VALUES (@StudentID, @FirstName, @LastName, @EnrollmentDate)";
SqlCommand insertCommand = new SqlCommand(insertQuery, conn);
insertCommand.Parameters.AddWithValue("@StudentID", 1);
insertCommand.Parameters.AddWithValue("@FirstName", "John");
insertCommand.Parameters.AddWithValue("@LastName", "Doe");
insertCommand.Parameters.AddWithValue("@EnrollmentDate", DateTime.Now);
insertCommand.ExecuteNonQuery();
四、查询数据
1、使用SqlDataReader读取数据:
SqlDataReader用于从数据库中逐行读取数据。
string selectQuery = "SELECT * FROM Students";
SqlCommand selectCommand = new SqlCommand(selectQuery, conn);
SqlDataReader reader = selectCommand.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"{reader["FirstName"]} {reader["LastName"]}");
}
reader.Close();
2、使用DataTable和DataAdapter:
DataTable和SqlDataAdapter可以用于将查询结果填充到内存中的表格结构中。
DataTable dataTable = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(selectQuery, conn);
adapter.Fill(dataTable);
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine($"{row["FirstName"]} {row["LastName"]}");
}
五、更新数据
1、使用SqlCommand更新数据:
通过执行UPDATE语句来修改表中的数据。
string updateQuery = "UPDATE Students SET LastName = @LastName WHERE StudentID = @StudentID";
SqlCommand updateCommand = new SqlCommand(updateQuery, conn);
updateCommand.Parameters.AddWithValue("@StudentID", 1);
updateCommand.Parameters.AddWithValue("@LastName", "Smith");
updateCommand.ExecuteNonQuery();
六、删除数据
1、使用SqlCommand删除数据:
通过执行DELETE语句来从表中移除数据。
string deleteQuery = "DELETE FROM Students WHERE StudentID = @StudentID";
SqlCommand deleteCommand = new SqlCommand(deleteQuery, conn);
deleteCommand.Parameters.AddWithValue("@StudentID", 1);
deleteCommand.ExecuteNonQuery();
七、事务处理
1、使用SqlTransaction管理事务:
事务确保了一系列操作要么全部成功,要么全部失败,以保持数据的一致性。
SqlTransaction transaction = conn.BeginTransaction();
try
{
// 执行多个数据库操作
transaction.Commit(); // 如果所有操作成功,提交事务
}
catch (Exception ex)
{
transaction.Rollback(); // 如果任何一个操作失败,回滚事务
throw;
}
八、使用Entity Framework Core简化数据库操作

1、安装Entity Framework Core:
通过NuGet包管理器安装Entity Framework Core。
Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
2、DbContext和实体类:
定义一个DbContext类和一个或多个实体类来映射数据库表。
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
public class Student
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
3、迁移和种子数据:
使用迁移来生成数据库,并使用种子数据初始化表。
Add-Migration InitialCreate
Update-Database
4、CRUD操作:
使用LINQ to Entities进行查询和操作。
using (var context = new SchoolContext())
{
// 添加新学生
var student = new Student { FirstName = "Jane", LastName = "Doe", EnrollmentDate = DateTime.Now };
context.Students.Add(student);
context.SaveChanges();
// 查询学生
var students = context.Students.ToList();
foreach (var std in students)
{
Console.WriteLine($"{std.FirstName} {std.LastName}");
}
}
在ASP.NET中操作数据库表涉及到连接数据库、执行CRUD(创建、读取、更新、删除)操作以及事务处理等多个方面,Entity Framework Core提供了一种更高级的方式来简化这些操作,使得开发者可以更加专注于业务逻辑而不是底层的数据库细节。
小伙伴们,上文介绍了“asp.net 数据库表”的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。