C# 中查询数据库数据的步骤
第一步:建立连接
建立与数据库的连接是访问数据库数据的关键。使用
System.Data.SqlClient命名空间中的
SqlConnection类。例如:
<code class="c#">using (SqlConnection conn = new SqlConnection("connection string"))
{
// 数据库操作
}</code>第二步:创建命令
创建一个
SqlCommand对象来指定要执行的查询。例如:
<code class="c#">SqlCommand cmd = new SqlCommand("SELECT * FROM TableName", conn);</code>第三步:执行查询
使用
ExecuteReader()方法执行查询并获取
SqlDataReader对象。此对象提供访问结果集中记录的能力。例如:
<code class="c#">using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// 访问每行的列
}
}</code>第四步:获取和处理数据
使用
reader的
Get方法访问结果集中的列值。这些值可以是字符串、数字或其他数据类型。例如:
<code class="c#">string name = reader.GetString(0); int age = reader.GetInt32(1);</code>
第五步:关闭连接
使用命令的
Dispose()方法和连接的
Close()方法释放资源。例如:
<code class="c#">cmd.Dispose(); conn.Close();</code>
