DataTable
是 C# 中的一个类,属于 System.Data
命名空间,主要用于处理数据库中的表格数据。它提供了一种灵活的方式来存储和操作数据,类似于数据库中的表。
DataRow
和 DataColumn
。DataTable
中的数据。DataSet
结合使用,支持数据的序列化和反序列化。DataTable
本身没有子类型,但可以通过添加不同的 DataColumn
来存储不同类型的数据(如 int
, string
, DateTime
等)。
以下是一个简单的示例,展示了如何创建和使用 DataTable
:
using System;
using System.Data;
class Program
{
static void Main()
{
// 创建一个新的 DataTable
DataTable table = new DataTable("Employees");
// 添加列
table.Columns.Add("EmployeeID", typeof(int));
table.Columns.Add("FirstName", typeof(string));
table.Columns.Add("LastName", typeof(string));
table.Columns.Add("BirthDate", typeof(DateTime));
// 添加行
table.Rows.Add(1, "John", "Doe", new DateTime(1980, 5, 15));
table.Rows.Add(2, "Jane", "Smith", new DateTime(1975, 8, 20));
// 显示数据
foreach (DataRow row in table.Rows)
{
Console.WriteLine($"ID: {row["EmployeeID"]}, Name: {row["FirstName"]} {row["LastName"]}, BirthDate: {row["BirthDate"]}");
}
}
}
DataTable
中的空值?解决方法: 使用 DBNull.Value
表示空值。
table.Rows.Add(3, "Alice", null, DBNull.Value);
DataTable
转换为 JSON?解决方法: 使用 Newtonsoft.Json
库进行序列化。
using Newtonsoft.Json;
string json = JsonConvert.SerializeObject(table);
Console.WriteLine(json);
DataTable
?解决方法: 使用 SqlDataAdapter
或其他数据适配器。
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection("your_connection_string");
SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);
通过这些方法和示例代码,你可以更好地理解和使用 DataTable
在 C# 中进行数据处理。
领取专属 10元无门槛券
手把手带您无忧上云