在我的应用程序中,用户将插入一本书。例如 someBook 将插入 3 个副本。Table1.BookID = 1,Table1.Copy = 3,然后在另一个表中,这 3 本书将有它们的主键,因此它将是 Table2.AccessionID = 1,2,3 Table2.BookID = 1,1,1。
这是我目前正在做的,但正如 Aaron Bertrand 所说的那样,这是一种不好的做法。
int BookTitlesID;
public void addBookTitle()
{
int copy = int.Parse(textBox2.Text);
try
{
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand1 = new SqlCommand("INSERT INTO BookTitles(BookTitle, Copies) Values(@BookTitle, @Copies)", myDatabaseConnection))
{
mySqlCommand1.Parameters.AddWithValue("@BookTitle", BookTitletextBox.Text);
mySqlCommand1.Parameters.AddWithValue("@Copies", copy);
mySqlCommand1.ExecuteNonQuery();
}
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "Exception");
}
}
public void addBook()
{
int copy = int.Parse(textBox2.Text);
try
{
for (int x = 0; x < copy; x++)
{
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand1 = new SqlCommand("INSERT INTO book(BookTitleID) Values(@BookTitleID)", myDatabaseConnection))
{
mySqlCommand1.Parameters.AddWithValue("@BookTitleID", BookTitlesID);
mySqlCommand1.ExecuteNonQuery();
}
}
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "Exception");
}
}
private void Form_Load(object sender, EventArgs e)
{
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand1 = new SqlCommand("SELECT TOP 1 BookTitleID + 1 FROM BookTitles ORDER BY BookTitleID DESC", myDatabaseConnection))
{
string x = mySqlCommand1.ExecuteScalar().ToString();
BookTitlesID = Convert.ToInt32(x);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
addBookTitle();
addBook();
}