【问题标题】:Selecting a value from one table to insert the id of the row to another one in asp.net从一个表中选择一个值以将行的 id 插入到 asp.net 中的另一个表中
【发布时间】:2013-04-29 20:51:07
【问题描述】:

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

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

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

查询此 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:我应该为这个简单的任务创建一个存储过程吗?

【问题讨论】:

    标签: c# asp.net tsql ado.net


    【解决方案1】:

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

    我已经在下拉列表中找到了产品名称

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

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

    然后在代码隐藏中传递/获取该值,类似于从txtAmount 获取金额的值。通过这种方式,您不必为了获取 _ProductID 而按名称查询 products 表,因此您可以将其插入到 ORDERS 表中。

    【讨论】:

    • 是的,您可能想要修复您拥有的那个 sql。要么使用存储过程,要么如果你不喜欢它,至少参数化该查询,例如:INSERT INTO ORDERS (_Date) VALUES (@date)See this easy to understand example
    • 好吧,我用简单的笨方法做这件事:一会儿遍历按产品 id 排序的列表,当它的 == 到所选值时,它停止添加到 int 变量和然后我用它将产品ID存储在数据库中。谢谢你。
    • 不客气。尽管我对您的最后评论有点迷茫,但我想您已经解决了您的问题,因为您已经接受了我的回答。如果没有,请在这里告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 2013-09-05
    • 2014-07-29
    • 1970-01-01
    相关资源
    最近更新 更多