连接表,插入和选择

时间:2012-07-01 15:54:23

标签: c# asp.net sql sql-server relational-database

enter image description here

我自己学习这个,并且我已经达到了我想要插入新类别和新国家的程度,但我不知道该怎么做。

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

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

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

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

1 个答案:

答案 0 :(得分:1)

像这样发送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方法之一总是可能抛出异常,无论是超时还是网络问题。

相关问题