發(fā)布時(shí)間:2020-08-07 05:25 作者:獨(dú)孤劍 閱讀:2065
C# 操作SQL Server數(shù)據(jù)庫(kù), 執(zhí)行T-SQL語(yǔ)句, 將記錄結(jié)果填充到DataTable中
創(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');
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 (DataTable dt = new DataTable()) { using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { da.Fill(dt); } // return dt; } } catch { throw; } } } Console.Read(); } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對(duì)您有幫助,歡迎給作者打賞