I just started sql and have a problem that I have been dealing with for days.
I have two data tables. The first is the book, the second is the author. The fields of the book table:
Book
Book ID (PK)
AuthorID
BookName
...
Author
AuthorID (PK)
Author Name
What I want to do here is to create the database for the author while the book is registered.
1-Book Name, Author name will be written in the textboxes in the Windows form application and the save button will be clicked. The author name will first be saved in the 'author' table and the id as the automatic pk key will be created.
2-The 'author name' written on the textbox and the corresponding id in the author table will be taken.
3- Finally, the title of the book and the author id will be recorded in the "book" table.
To give an example:
To textboxes in the Windows form application:
Book Title: IT
Author Name: Stephen King
Hit the save button.
Author table
AuthorID: 97 (automatically assigned)
Author Name: Stephen King
Book table
Book ID: 11
AuthorID: 97
Book Name: IT
In short, with a single click, there is both an author and a book record and a database at the same time.
I have tried many methods, but I cannot store the Author ID I took.
string sqlcom1 = "INSERT INTO author (authorName) VALUES(@Pauthor)";
commandObject = new SqlCommand(sqlcom1, connectionObject );
commandObject.Parameters.AddWithValue("@Pauthor", textBoxauthorName.Text);
string sqlcom2 = "SELECT authorID FROM author WHERE authorName='" + textBoxauthorName.Text + "'");
commandObject = new SqlCommand(sqlcom2 , connectionObject );
string sqlcom3 = "INSERT INTO book (bookName,authorID) VALUES(@PbookName,@PauthorID)";
commandObject = new SqlCommand(sqlcom3, connectionObject);
commandObject.Parameters.AddWithValue("@PbookName", textBoxbookName.Text);
commandObject.Parameters.AddWithValue("@PauthorID", sqlcom2);
connectionObject.Open();
commandObject.ExecuteNonQuery();
connectionObject.Close();
Error: 'Conversion failed when converting the nvarchar value 'SELECT authorID FROM author WHERE authorName='author30'' to data type int.'
author30 --> The value I entered into the textbox for the author name.
Note: I can see that by registering to the author table, names are automatically assigned ids. Registration to the author table is taking place.
The author ID is associated with the author ID in the book table.