简体   繁体   English

连接表,插入和选择

[英]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: 像这样发送SQL:

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. 这将返回新添加的类别的ID作为行集。 You can retrieve the new ID using the familiar ExecuteReader() : 您可以使用熟悉的ExecuteReader()检索新ID:

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

Or even shorter with ExecuteScalar() : 甚至用ExecuteScalar()更短:

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

And by the way, consider wrapping your connection in using : 顺便说一下,请考虑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. 无论是超时还是网络问题, Execute方法之一总是有可能引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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