They have relation between AuthorID and AID
I want to add attributes to 2 tables at the same time
public static bool AddNewPackage(BookCitation package)
{
MySqlConnection connection = DataAccess.getConnection();
string insertStatement =
@"INSERT into Book (
AuthorName,
PubYear,
BookTitle,
PubCity,
PubName,
PageNumbers)
VALUES (
@AuthorName,
@PubYear,
@BookTitle,
@PubCity,
@PubName,
@PageNumbers);
INSERT into Author (
AID,
AuthorNamee,
Affiliation)
VALUES (@AID, @AuthorNamee, @Affiliation)";
MySqlCommand insertCommand = new MySqlCommand(insertStatement, connection);
insertCommand.Parameters.AddWithValue("@AID", package.AID);
insertCommand.Parameters.AddWithValue("@AuthorName", package.AuthorName);
insertCommand.Parameters.AddWithValue("@AuthorNamee", package.AuthorNamee);
insertCommand.Parameters.AddWithValue("@Affiliation", package.Affiliation);
insertCommand.Parameters.AddWithValue("@PubYear", package.PublishYear);
insertCommand.Parameters.AddWithValue("@BookTitle", package.BookTitle);
insertCommand.Parameters.AddWithValue("@PubCity", package.PublisherCity);
insertCommand.Parameters.AddWithValue("@PubName", package.Publisher);
insertCommand.Parameters.AddWithValue("@PageNumbers", package.PageNumbers);
try
{
connection.Open();
insertCommand.ExecuteNonQuery();
return true;
}
catch (SqlException ex)
{
MessageBox.Show(ex.GetType() + ex.Message);
return false;
}
finally
{
connection.Close();
}
}
public class BookCitation
{
public int BookCID { get; set; }
public int AID { get; set; }
public string AuthorName { get; set; }
public string AuthorNamee { get; set; }
public string Affiliation { get; set; }
public DateTime PublishYear { get; set; }
public string BookTitle { get; set; }
public string PublisherCity { get; set; }
public string Publisher { get; set; }
public string PageNumbers { get; set; }
}
如何使用外键添加AuthorID?
答案 0 :(得分:0)
该错误消息表示作者必须首先存在。插入新作者,检索该新作者的AID,然后插入新书,并将该书的AID列设置为与您刚刚插入的新作者的检索AID值相同的值