0

我正在我的项目中尝试最简单的插入实现来学习并将其展示给我未来的雇主。我知道我应该把它放在另一层并调用它等,但老实说我没有足够的时间,无论如何我需要学习如何以简单的方式做到这一点。

我已经在 SESSION["USER"] 中存储了“@username”,现在我需要在 ORDERS 表中插入金额和产品 ID,问题是产品名称在 PRODUCTS 表中。

我已经在下拉列表中有产品名称,因此 USER 选择值,输入金额,然后单击 BUY 并将 ORDER 存储在数据库中。

查询此 SQL 命令的正确方法是什么?我在想 SqlCommand 会做的伎俩,但我仍然不太确定如何把它。

来自数据库的样本:

CREATE TABLE ORDERS
(
_OrderID int not null identity (1,1) primary key,
_Date datetime null,
_Quantity bigint null,
_ProdID int foreign key references PRODUCTS (_ProductID),
_UserID int foreign key references USERS (_UserID)
)
GO


CREATE TABLE PRODUCTS
(
_ProductID int not null identity(1,1) primary key,
_ProdName nchar (200) null,
_StockUnits int,
_SuppID int foreign key references SUPPLIERS (_SuppID)
)
GO

CREATE TABLE USERS
(
_UserID int not null identity(1,1) primary key,
_UserEmail varchar (35) null,
_UserName varchar (30) not null,
_UserPass varchar (30) not null,
_Name varchar (100),
_Phone varchar (20) null,
_Address varchar (150) null,
_Authority int not null,
_Special bit null
)
GO

 protected void btnBuy_Click(object sender, EventArgs e)
        {
           //obviously incomplete.
            string usrQuery = Session["NOMUSU"].ToString();
            SqlConnection oConnection = new SqlConnection("Server=.\\SQLExpress;AttachDbFilename=L:\\Apps\\VS Projects\\Carnisoftix\\CarniDb.mdf;Database=CarniDb;Trusted_Connection=Yes;");
            SqlCommand oCom = new SqlCommand("INSERT INTO ORDERS _Date, _Quantity VALUES " + " (" + DateTime.Now.ToString("yyyy-mm-dd HH:mm:ss") + ", "+ txtAmount.Text 
        }

PD:我应该为这个简单的任务创建一个存储过程吗?

4

1 回答 1

1

您的问题的关键在于您的以下陈述:

我已经在下拉列表中有产品名称

当您构建该下拉列表时,您可以添加Id产品并将其用作下拉列表中的值,这样您将拥有如下内容:

<select>
    <option value="1">Apple</option>
    <option value="2">Banana</option>
    <option value="3">Orange</option>
</select>

然后你在你的代码隐藏中传递/获取该值,类似于你如何从txtAmount. 以这种方式,您不必为了获取产品表的名称而查询产品表,_ProductID这样您就可以将其插入ORDERS表中。

于 2013-05-06T06:25:32.873 回答