發(fā)布時(shí)間:2020-08-07 05:27 作者:獨(dú)孤劍 閱讀:2103
C# 操作SQL Server數(shù)據(jù)庫, 參數(shù)化執(zhí)行T-SQL語句, 將記錄結(jié)果填充到DataTable中
創(chuàng)建SQL Server數(shù)據(jù)庫、數(shù)據(jù)表:
USE master; GO --創(chuàng)建數(shù)據(jù)庫 IF NOT EXISTS(SELECT * FROM dbo.sysdatabases WHERE [name]='TestDB') CREATE DATABASE TestDB; GO --使用數(shù)據(jù)庫 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 (DataTable dt = new DataTable()) { using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { da.Fill(dt); } // return dt; } } catch { throw; } } } Console.Read(); } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對(duì)您有幫助,歡迎給作者打賞