简体   繁体   中英

How to add data from 2 tables into one using access database in c# wpf

I'm trying to add data from two tables in database into one table, but i'm having some difficulties with the code. I need to create an option for users to book a train ticket, and their ID and the ticket's ID needs to be displayed in new table (reservations)

Here is and example:

User:
ID: 5
Name: Jack
Last Name: Jones

Ticket:
ID: 9
Name: London

RESULT

Booking table:
BookingId: 1
UserId: 5
BookId: 9

This is my code so far

try
{
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = myConnection;
    cmd.CommandText = "SELECT User.ID, Ticket.ID AS Reservation FROM (User INNER JOIN Ticket ON User.ID = Ticket.ID)";
    cmd.CommandText = "INSERT INTO Reservation(ID_user, ID_ticket)" + "values(@User.ID, @Ticket.ID)";
    myConnection.Open();
    cmd.ExecuteNonQuery();
    MessageBox.Show("Ticket added");
    myConnection.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

Please help me out!

Assuming that Booking table and Reservation table is one and the same. If not then comment here.

If I understand your business correctly, first and foremost thing is you cannot have a join on User table and Ticket table based on their id. They are independent tables and do not have a relationship between them.

Secondly both the data ie userid and ticketid should be available on the UI when the user finally books the ticket.

As for userid, if you have an asp.net application, the userid will be available when s/he logs on to your website, else if it is a windows application you can save it in a public static class variable.

The ticketid will be the record the user selects when it adds the details of his/her journey.

You need to pick them and add it in the reservations table.

Hope this gives you some direction.

SELECT User.ID, Ticket.ID AS Reservation FROM (User INNER JOIN Ticket ON User.ID = Ticket.ID)

这里的条件是错误的,userid和ticketid将如何相等?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM