如何在 Visual Studio 中从 SQL 脚本创建数据库并将其添加到项目中?

Posted

技术标签:

【中文标题】如何在 Visual Studio 中从 SQL 脚本创建数据库并将其添加到项目中?【英文标题】:How to create a Database from SQL script inside Visual Studio and add it to the project? 【发布时间】:2021-07-11 00:47:28 【问题描述】:

我有一个 SQL 文件,它创建了我的 WPF 项目所需的数据库。但是,我知道如何构建数据库的唯一方法是从头开始,但我的代码实际上具有删除数据库的 SQL 命令,然后使用这些表中的表和信息重新创建它。我将如何运行这个脚本?我尝试按照本网站上已经发布的一些示例进行操作,但它们要么太旧,要么不完全适用于我的情况。

我已经在我的项目中安装了 NuGet 包:

Microsoft.EntityFrameworkCore.SqlServer (v5.0.4) Microsoft.EntityFrameworkCore.Tools (v5.0.4) Microsoft.EntityFrameworkCore.SqlServer.Design (v2.0.0)

我尝试在没有删除数据库和创建数据库的命令的情况下运行 SQL 脚本,但出现错误

对象“表产品”已经存在

USE master; 
GO 
 
--Delete the OMS (Order Management System) database if it exists. 
IF EXISTS(SELECT * from sys.databases WHERE name='OMS') 
BEGIN 
    DROP DATABASE OMS; 
END 

CREATE DATABASE OMS;
GO

USE OMS;
GO

CREATE TABLE Product 
( 
     idProduct SMALLINT PRIMARY KEY NOT NULL,
     ProductName varchar(25),
     Description varchar(100),
     Price DECIMAL(6,2)
);
           
INSERT INTO Product (idProduct, ProductName, Description, Price) 
VALUES (1, 'CapressoBar Model #351', 'A fully programmable pump espresso machine and 10-cup coffee maker complete with GoldTone filter', 99.99);

INSERT INTO Product (idProduct, ProductName, Description, Price) 
VALUES (2,'Capresso Ultima', 'Coffee and Espresso and Cappuccino Machine. Brews from one espresso to two six ounce cups of coffee', 129.99);

INSERT INTO Product (idProduct, ProductName, Description, Price) 
VALUES (3,'Eileen 4-cup French Press', 'A unique coffeemaker from those proud craftsmen in windy Normandy.', 32.50);

INSERT INTO Product (idProduct, ProductName, Description,Price) 
VALUES (4,'Coffee Grinder', 'Avoid blade grinders! This mill grinder allows you to choose a fine grind to a coarse grind.', 28.50);

INSERT INTO Product (idProduct, ProductName, Description,Price) 
VALUES (5,'Sumatra', 'Spicy and intense with herbal aroma. ', 10.50);

INSERT INTO Product (idProduct, ProductName, Description,Price) 
VALUES (6,'Guatamala', 'heavy body, spicy twist, aromatic and smokey flavor.', 10.00);

INSERT INTO Product (idProduct, ProductName, Description,Price) 
VALUES (7,'Columbia', 'dry, nutty flavor and smoothness',10.80);

INSERT INTO Product (idProduct, ProductName, Description,Price) 
VALUES (8,'Brazil', 'well-balanced mellow flavor, a medium body with hints of cocoa and a mild, nut-like aftertaste', 10.80);

INSERT INTO Product (idProduct, ProductName, Description,Price) 
VALUES (9,'Ethiopia', 'distinctive berry-like flavor and aroma, reminds many of a fruity, memorable wine. ', 10.00);

INSERT INTO Product (idProduct, ProductName, Description,Price) 
VALUES (10,'Espresso', 'dense, caramel-like sweetness with a soft acidity. Roasted somewhat darker than traditional Italian.',  10.00);

  
CREATE TABLE Shopper 
(
    idShopper INT PRIMARY KEY NOT NULL,
    Email varchar(25) not null,
    FirstName varchar(15),
    LastName varchar(20),
    Address varchar(40),
    City varchar(20),
    StateProvince varchar(20),
    Country varchar(20),
    ZipCode varchar(15)
);

INSERT INTO Shopper (idshopper, FirstName, LastName, Address, City, StateProvince, Country, ZipCode, Email)
VALUES (21, 'John', 'Carter', '21 Front St.', 'Raleigh','NC','USA','54822', 'Crackjack@aol.com');
INSERT INTO Shopper (idshopper, FirstName, LastName, Address, City, StateProvince, Country, ZipCode, Email)
VALUES (22, 'Margaret', 'Somner', '287 Walnut Drive', 'Cheasapeake', 'VA','USA','23321', 'MargS@infi.net');
INSERT INTO Shopper (idshopper, FirstName, LastName, Address, City, StateProvince, Country, ZipCode, Email)
VALUES (23, 'Kenny', 'Ratman', '1 Fun Lane', 'South Park', 'NC','USA','54674',  'ratboy@msn.net');
INSERT INTO Shopper (idshopper, FirstName, LastName, Address, City, StateProvince, Country, ZipCode, Email)
VALUES (24, 'Camryn', 'Sonnie', '40162 Talamore', 'South Riding','VA','USA','20152','kids2@xis.net');
INSERT INTO Shopper (idshopper, FirstName, LastName, Address, City, StateProvince, Country, ZipCode, Email)
VALUES (25, 'Scott', 'Savid', '11 Pine Grove', 'Hickory', 'VA','USA','22954',  'scott1@odu.edu');
INSERT INTO Shopper (idshopper, FirstName, LastName, Address, City, StateProvince, Country, ZipCode, Email)
VALUES (26, 'Monica', 'Cast', '112 W. 4th', 'Greensburg','VA','USA','27754', 'gma@earth.net');
INSERT INTO Shopper (idshopper, FirstName, LastName, Address, City, StateProvince, Country, ZipCode, Email)
VALUES (27, 'Pete', 'Parker', '1 Queens', 'New York','NY','USA','67233', 'spider@web.net');
  

CREATE TABLE Basket
(
    idBasket INT PRIMARY KEY NOT NULL,
    idShopper INT,
    Quantity TINYINT,
    SubTotal DECIMAL(7,2),
    OrderDate datetime not null,
    CONSTRAINT bskt_idshopper_fk FOREIGN KEY (idShopper) REFERENCES Shopper(idShopper) 
);

insert into Basket(idbasket, quantity, idshopper,subtotal,OrderDate)
    values (3, 3, 21,26.60,'23-JAN-2019');
insert into Basket (idbasket, quantity, idshopper,subtotal,OrderDate)
    values (4, 1, 21, 28.50,'12-FEB-2020');
insert into Basket(idbasket, quantity, idshopper,subtotal,OrderDate)
    values (5, 4, 22, 41.60, '19-FEB-2020');
insert into Basket(idbasket, quantity, idshopper,subtotal,OrderDate)
    values (6, 3, 22, 149.99, '01-MAR-2020');
insert into Basket(idbasket, quantity, idshopper,subtotal,OrderDate)
    values (7, 2, 23, 21.60,'26-JAN-2019');
insert into Basket(idbasket, quantity, idshopper,subtotal,OrderDate)
    values (8, 2, 23, 21.60,'16-FEB-2021');
insert into Basket(idbasket, quantity, idshopper,subtotal,OrderDate)
    values (9, 2, 23, 21.60,'02-MAR-2021');
insert into Basket(idbasket, quantity, idshopper,subtotal,OrderDate)
    values (10, 3, 24, 38.90,'07-FEB-2020');
insert into Basket(idbasket, quantity, idshopper,subtotal,OrderDate)
    values (11, 1, 24, 10.00, '27-FEB-2021');
insert into Basket(idbasket, quantity, idshopper,subtotal,OrderDate)
    values (12, 7, 25, 72.40, '19-FEB-2020');
insert into Basket(idbasket, quantity, idshopper,subtotal,OrderDate)
    values (15, 2, 27, 16.20,'14-FEB-2021');
insert into Basket (idbasket, quantity, idshopper,subtotal,OrderDate)
    values (16, 2, 27, 21.69, '24-FEB-2021');


CREATE TABLE BasketItem (
    idBasketItem INT PRIMARY KEY NOT NULL,
    idProduct SMALLINT,
    Quantity TINYINT,
    idBasket INT,
    CONSTRAINT bsktitem_bsktid_fk FOREIGN KEY (idBasket) REFERENCES Basket(idBasket),
    CONSTRAINT bsktitem_idprod_fk FOREIGN KEY (idproduct) REFERENCES Product(idproduct));

insert into BasketItem
      values (15, 6, 1, 3);
insert into BasketItem
      values (16, 8,  2, 3);
insert into BasketItem
      values (17, 4, 1, 4);
insert into BasketItem
      values (18, 7, 1, 5);
insert into BasketItem
      values (19, 8, 1, 5);
insert into BasketItem
      values (20, 9,1, 5);
insert into BasketItem
      values (21, 10, 1, 5);
insert into BasketItem
      values (22, 10, 2, 6);
insert into BasketItem
      values (23, 2, 1, 6);
insert into BasketItem
      values (24, 7, 1, 7);
insert into BasketItem
      values (25, 8, 1, 7);
insert into BasketItem
      values (26, 7, 1, 8);
insert into BasketItem
      values (27, 8, 1, 8);
insert into BasketItem
      values (28, 7, 1, 9);
insert into BasketItem
      values (29, 8, 1, 9);
insert into BasketItem
      values (30, 6, 1, 10);
insert into BasketItem
      values (31, 8, 1, 10);
insert into BasketItem
      values (32, 4, 1, 10);
insert into BasketItem
      values (33, 9, 1, 11);
insert into BasketItem
      values (34, 8, 2, 12);
insert into BasketItem
      values (35, 9, 2, 12);
insert into BasketItem
      values (36, 6, 2, 12);
insert into BasketItem
      values (37, 7, 1, 12);
insert into BasketItem
      values (40, 8, 1, 15);
insert into BasketItem
      values (41, 7, 1, 15);
insert into BasketItem
      values (42, 8, 1, 16);
insert into BasketItem
      values (43, 7, 1, 16);

我已经下药并删除了 SQL 脚本,它在我的 (localdb)\MSSQLLocalDB 中正常执行:

【问题讨论】:

请显示SQL代码和c#代码。在 SSMS 中运行 SQL 代码是否正常工作? 显示 SQL 脚本。据说它运行正常。还没有涉及 C# 代码,我只是想将数据库附加到我现有的项目中。我想我需要做这样的事情:docs.microsoft.com/en-us/previous-versions/… 你将如何读取代码中的数据? 使用 MVVM 模式并创建视图(例如 MainWindow)。 【参考方案1】:

尝试将脚本拆分为单独的命令并使用两个数据库连接。

到数据库=master 的一个数据库连接。您可以使用该数据库删除并重新创建 OMS 数据库。

const string connectionString1 = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;";
using (SqlConnection cn1 = new SqlConnection(connectionString1)) 
    cn1.Open();
    string[] cmds =  
        @"
            --Delete the OMS (Order Management System) database if it exists. 
            IF EXISTS(SELECT * from sys.databases WHERE name='OMS') 
            BEGIN 
                DROP DATABASE OMS; 
            END 
        ", @"
            CREATE DATABASE OMS;
        ";
    using (SqlCommand cmd = new SqlCommand()) 
        cmd.Connection = cn1;
        foreach (string sql in cmds) 
            cmd.CommandText = sql;
            int recordsAffected = cmd.ExecuteNonQuery();
            Console.WriteLine($"Executed sql Command 'sql', recordsAffected record(s) affected.");
        
    

其他连接默认为database=OMS。您可以使用它来创建数据库对象。

const string connectionString2 = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=OMS;Integrated Security=True;";
using (SqlConnection cn2 = new SqlConnection(connectionString2)) 
    cn2.Open();
    string[] cmds =  
        "CREATE TABLE Product ...",
        "insert into Product( ..."
    ;
    using (SqlCommand cmd = new SqlCommand()) 
        cmd.Connection = cn2;
        foreach (string sql in cmds) 
            cmd.CommandText = sql;
            int recordsAffected = cmd.ExecuteNonQuery();
            Console.WriteLine($"Executed sql Command 'sql', recordsAffected record(s) affected.");
        
    

【讨论】:

我重新安装了 NuGet 包 Microsoft.EntityFrameworkCore.SqlServer 、 Microsoft.EntityFrameworkCore.Tools,我终于能够使用 Scaffold-DbContext 命令在我的模型文件夹中构建类。我不知道在那之前我对他们做错了什么。 我忘了再提一个 NuGet 包:Microsoft.EntityFrameworkCore.SqlServer.Design

以上是关于如何在 Visual Studio 中从 SQL 脚本创建数据库并将其添加到项目中?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 VIsual Studio 2013 中从 UML 图生成 C++ 代码

如何在 Visual Studio 2013 中从 C# 解决方案生成序列图?

如何在 Mac 终端中从 Visual Studio 运行应用程序

如何在 Windows 10 中从命令行构建 Visual Studio 2015 vb 解决方案

如何在 Visual Studio 中从数据库中获取数据(使用 C#)时使 HTML 行可点击

在 Visual Studio 2010 中从 .NET 项目启动 C++ 项目