简体   繁体   中英

Junction Table, Insert and Select

在此处输入图片说明

I'm learning this on my own, and i've reached a point where I want to insert new Categories and new Countries but I don't know how to do that exactly.

For instance to add a new category I do the following:

public int Insert()
{
    string sqlString = "INSERT INTO Categories (name, image) VALUES (@Name, @Image);";
    SqlConnection sqlConnection = new
       SqlConnection(ConfigurationManager.ConnectionStrings["OahuDB"].ConnectionString);
    SqlCommand sqlCommand = new SqlCommand(sqlString, sqlConnection);
    sqlCommand.Parameters.AddWithValue("@Name", this.Name);
    sqlCommand.Parameters.AddWithValue("@Image", this.Image);
    sqlConnection.Open();
    int x = sqlCommand.ExecuteNonQuery();
    sqlConnection.Close();
    sqlConnection.Dispose();
    return x;
}

But how should I insert the relationship between both tables and then retrieve data based on the junction table?

If you could give examples and good tutorials on this or if you could elaborate a little bit. Thanks alot.

Send SQL like this:

INSERT INTO Categories (name, image) VALUES (@Name, @Image);
SELECT scope_identity() as NewCategoryId;

This will return the ID of the newly added category as a rowset. You can retrieve the new ID using the familiar ExecuteReader() :

using (var read = sqlCommand.ExecuteReader())
{
    read.Read();
    int newCategoryId = (int) read["NewCategoryId"];
}

Or even shorter with ExecuteScalar() :

int newId = (int)sqlCommand.ExecuteScalar();

And by the way, consider wrapping your connection in using :

using (var sqlConnection = new SqlConnection("...connection string...")
{
    sqlConnection.Open();
    var sqlCommand = sqlConnection.CreateCommand();
    ...
}

That helps guard against connection leaks. It's always possible that one of the Execute methods throws an exception, whether it's a timeout or a network issue.

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