位置:首页 > 编程专栏 > C#

C# 操作SQL Server数据库, 执行T-SQL语句, 将记录结果填充到DataSet中

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();
        }
    }
}


C# 社区推荐