繁体   English   中英

连接表,插入和选择

[英]Junction Table, Insert and Select

在此处输入图片说明

我正在独自学习这一点,现在我想插入新的类别和新的国家,但是我不知道该怎么做。

例如,要添加新类别,请执行以下操作:

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;
}

但是,我应该如何插入两个表之间的关系,然后根据联结表检索数据?

如果您可以为此提供示例和良好的教程,或者可以详细说明一下。 非常感谢。

像这样发送SQL:

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

这将返回新添加的类别的ID作为行集。 您可以使用熟悉的ExecuteReader()检索新ID:

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

甚至用ExecuteScalar()更短:

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

顺便说一下,请考虑using以下方式包装连接:

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

这有助于防止连接泄漏。 无论是超时还是网络问题, Execute方法之一总是有可能引发异常。

暂无
暂无

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

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