發布時間:2020-08-07 05:28 作者:獨孤劍 閱讀:1520
C# 操作SQL Server數據庫, 執行T-SQL語句, 將記錄結果填充到DataSet中
創建SQL Server數據庫、數據表:
USE master; GO --創建數據庫 IF NOT EXISTS(SELECT * FROM dbo.sysdatabases WHERE [name]='TestDB') CREATE DATABASE TestDB; GO --使用數據庫 USE TestDB; GO --創建用戶表 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];"; using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { conn.Open(); cmd.Connection = conn; cmd.CommandText = sqlstring; cmd.CommandType = System.Data.CommandType.Text; try { using (DataSet ds = new DataSet()) { using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { da.Fill(ds); } // return ds; } } catch { throw; } } } Console.Read(); } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞