Reputation: 2785
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.
Upvotes: 1
Views: 997
Reputation: 238126
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.
Upvotes: 1