發(fā)布時(shí)間:2020-08-07 05:30 作者:獨(dú)孤劍 閱讀:1838
C# 操作SQL Server數(shù)據(jù)庫(kù), 參數(shù)化執(zhí)行T-SQL語(yǔ)句, 將記錄結(jié)果填充到DataSet中
創(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)建用戶表 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] WHERE [Sex]=@Sex;"; 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; // 綁定參數(shù), 方式一 cmd.Parameters.AddWithValue("@Sex", "Male"); //// 綁定參數(shù), 方式二 //cmd.Parameters.Add("@Sex", SqlDbType.NVarChar); //cmd.Parameters["@Sex"].Value = "Male"; try { using (DataSet ds = new DataSet()) { using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { da.Fill(ds); } // return ds; } } catch { throw; } } } Console.Read(); } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對(duì)您有幫助,歡迎給作者打賞