using System.Data; // Use ADO.NET namespace
using System.Data.SqlClient;
SqlConnection thisConnection = new SqlConnection(
@"Data Source=GY; Initial Catalog=northwind;uid=sa;password=datadog"); //先建立连接
thisConnection.Open();//打开连接
SqlCommand thisCommand = thisConnection.CreateCommand();//直接指定conn的command
也可以这样 // SqlCommand cmd = new SqlCommand();
// cmd.Connection = thisConnection;
cmmand的sql命令
thisCommand.CommandText = "SELECT CustomerID, CompanyName from Customer";
SqlDataReader thisReader = thisCommand.ExecuteReader();//sqldatareader不可以用new 必须直接与command关联
//用reader读出表
while (thisReader.Read())
{
// Output ID and name columns
Console.WriteLine("/t{0}/t{1}",
thisReader["CustomerID"], thisReader["CompanyName"]);
// Close reader 用完要关闭
thisReader.Close();
// Close connection
thisConnection.Close ()
ADO.NET中的sql连接
最新推荐文章于 2026-06-22 20:28:17 发布
本文介绍了如何使用ADO.NET和SqlConnection、SqlCommand、SqlDataReader等组件连接并操作SQL Server数据库,包括建立连接、执行SQL查询、读取数据以及关闭资源。

5857

被折叠的 条评论
为什么被折叠?



