将两个表中的数据插入一个表C#

时间:2017-10-10 07:05:08

标签: c# sql sql-server listbox

嗨,将数据从两个表插入一个表的正确方法是什么,所以它们是3个表,我的第一个表Tbl_orderOrder_ID,第二个Tbl_Cashier有{ {1}}和第3个Cashier_IDTbl_FinalizedOrder_ID。表格的完整设计

Tbl_Cashier

Cashier_ID

Tbl_order

CREATE TABLE [dbo].[Tbl_Cashier] (
    [Cashier_ID] INT           IDENTITY (1, 1) NOT NULL,
    [FName]      VARCHAR (50)  NOT NULL,
    [MName]      VARCHAR (50)  NULL,
    [LName]      VARCHAR (50)  NOT NULL,
    [Address]    NVARCHAR (50) NOT NULL,
    [ContactNo]  VARCHAR (50)  NOT NULL,
    [Email]      NVARCHAR (50) NOT NULL,
    [Age]        INT           NOT NULL,
    [Gender]     VARCHAR (50)  NOT NULL,
    [Password]   VARCHAR (50)  NOT NULL,
    [role]       NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Cashier_ID] ASC)
); 

Tbl_Finalized

CREATE TABLE [dbo].[Tbl_order] (
    [Order_ID]   INT            IDENTITY (1, 1) NOT NULL,
    [CustomerNo] INT            NOT NULL,
    [OrderName]  NVARCHAR (MAX) NOT NULL,
    [Quantity]   INT            NOT NULL,
    [Price]      FLOAT (53)     NOT NULL,
    [Serves_way] INT            NOT NULL,
    [Date]       DATETIME       NOT NULL,
    PRIMARY KEY CLUSTERED ([Order_ID] ASC),
    CONSTRAINT [Serves_wayFK] FOREIGN KEY ([Serves_way]) REFERENCES [dbo].[Tbl_Serve] ([Serve_ID])
);

所以当我登录应用程序时,我使用FName和密码CREATE TABLE [dbo].[Tbl_Finalized] ( [Finalized_ID] INT IDENTITY (1, 1) NOT NULL, [Order_ID] INT NOT NULL, [Cashier_ID] INT NOT NULL, [Customer_ID] INT NOT NULL, PRIMARY KEY CLUSTERED ([Finalized_ID] ASC), CONSTRAINT [CashierFK] FOREIGN KEY ([Cashier_ID]) REFERENCES [dbo].[Tbl_Cashier] ([Cashier_ID]), CONSTRAINT [CustomerFK] FOREIGN KEY ([Customer_ID]) REFERENCES [dbo].[Tbl_Customer] ([Customer_ID]) ); 我登录,如何获取登录的Tbl_Cashier并将其插入Cashier_ID中的Cashier_ID?这是我的登录代码:

Tbl_Finalized

从应用程序我使用列表框将订单插入private void but_log_in_Click(object sender, EventArgs e) { if (tbx_username.Text == "" || Tbx_Password.Text == "") { MessageBox.Show("Please provide UserName and Password"); return; } try { using (SqlConnection con = new SqlConnection(connectionString)) using (SqlCommand cmd = new SqlCommand("Select * from Tbl_Cashier where FName=@username and Password=@password", con)) using (SqlDataAdapter adapt = new SqlDataAdapter(cmd)) { con.Open(); cmd.Parameters.AddWithValue("@username", tbx_username.Text); cmd.Parameters.AddWithValue("@password", Tbx_Password.Text); HabibisGrll.Globals.sss = tbx_username.Text; DataSet ds = new DataSet(); adapt.Fill(ds); con.Close(); int count = ds.Tables[0].Rows.Count; //If count is equal to 1, than show frmMain form if (count == 1) { MessageBox.Show("Login Successful!"); this.Hide(); HabibisGrll fm = new HabibisGrll(); fm.Show(); } else { MessageBox.Show("Login Failed!"); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } 我想插入Tbl_order我已经选择并从Order_ID插入到Tbl_order Order_ID。我的代码,从列表框

插入所有订单到数据库
Tbl_Finalized

1 个答案:

答案 0 :(得分:0)

在but_log_in_Click中,您将数据放入数据集中,第一个字段是收银员ID - 现在您已登录ID,将其保存在安全的地方