当前位置:数据库 > SQLServer >>

ADO.NET中的SQL连接方法代码

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(" {0} {1}",
thisReader["CustomerID"], thisReader["CompanyName"]);
// Close reader 用完要关闭
thisReader.Close();

// Close connection
thisConnection.Close ()

补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,