1

在此处输入图像描述

我正在自己学习这一点,并且我已经到了想要插入新类别和新国家/地区的地步,但我不知道该怎么做。

例如,要添加一个新类别,我会执行以下操作:

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

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

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

4

1 回答 1

1

像这样发送 SQL:

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

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

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引发异常。

于 2012-07-01T16:27:28.773 回答