發(fā)布時(shí)間:2020-08-07 05:22 作者:獨(dú)孤劍 閱讀:2076
將 CommandText 發(fā)送到 Connection,并生成 SqlDataReader。DataReader對(duì)象提供了游標(biāo)形式的讀取方式,當(dāng)從結(jié)果行中讀取了一行,則游標(biāo)會(huì)繼續(xù)讀取到下一行。通過(guò)read方法可以判斷數(shù)據(jù)是否還有下一行,如果存在數(shù)據(jù),則繼續(xù)運(yùn)行返回true,如果沒(méi)有數(shù)據(jù),則返回false。
創(chuàng)建SQL Server數(shù)據(jù)庫(kù)、數(shù)據(jù)表:
USE master; GO --創(chuàng)建數(shù)據(jù)庫(kù) IF NOT EXISTS(SELECT * FROM dbo.sysdatabases WHERE [name]='TestDB') CREATE DATABASE TestDB; GO --使用數(shù)據(jù)庫(kù) USE TestDB; GO --創(chuàng)建用戶(hù)表 IF EXISTS(SELECT * FROM sysobjects WHERE [name]='Users') DROP TABLE [Users] GO CREATE TABLE [Users]( [Id] [int] IDENTITY(1,1),--主鍵 [Name] [nvarchar](50) NOT NULL,--姓名 [Sex] [nvarchar](10),--性別 PRIMARY KEY([Name]) ); GO INSERT INTO [Users]([Name],[Sex]) VALUES ('Alice','Female'); INSERT INTO [Users]([Name],[Sex]) VALUES ('Amy','Female'); INSERT INTO [Users]([Name],[Sex]) VALUES ('Bruce','Male');
C#代碼:
using System; using System.Data; using System.Data.SqlClient; namespace SqlServerDemo { class Program { static void Main(string[] args) { string connectionString = "Data Source=127.0.0.1,1433;Initial Catalog=TestDB;uid=sa;pwd=123456"; string sqlstring = "SELECT * FROM [Users];"; SqlConnection conn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); try { conn.Open(); cmd.Connection = conn; cmd.CommandText = sqlstring; cmd.CommandType = System.Data.CommandType.Text; SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (reader.Read()) { if (reader.HasRows) { Console.WriteLine(reader.GetInt32(0) + " - " + reader.GetString(1) + " - " + reader.GetString(2)); } } } catch { if (conn.State != ConnectionState.Closed) { conn.Close(); } throw; } Console.Read(); } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對(duì)您有幫助,歡迎給作者打賞