Additional SQL Server features and topics not covered by specific categories
This part should be:
SqlCommand cmd = new SqlCommand("INSERT INTO CD VALUES(" + id + "," + Title + " ," + Artist + "," + Country + "," + Company +
"," + Price + ", " + Year + ")", con);
SqlCommand cmd = new SqlCommand(@"INSERT INTO CD(id, Title, Artist, Country, Company, Price, Year)
VALUES(@id, @Title, @Artist, @Country, @Company, @Price, @Year)", con);
cmd.Parameters.Add("@id", SqlDbType.Int).Value ) = id;
cmd.Parameters.Add("@Title", SqlDbType.NVarChar, 40).Value ) = Artist
and so on for remaining parameters.
Important points:
- Always specify a column list with INSERT, or else the code will break if someone adds a column to the table, even if that column is nullable.
- Use parameterised statements. That is simpler than trying to concatenate a query string. It also removes the risk for SQL injection. And the code will work even if you own albums by Gilbert O'Sullivan. Finally, it utilises the query cache in SQL Server a lot better.
- When building the parameters you need to specify the data types and for the strings also specify length. I had to make a guess here. You may need to adjust.
Does anybody know what is wrong or why it doesn't run?
Next time you ask a question of this kind, please specify what happens. That is, tell us what happens when you try. Do you get unexpected results? If you get an error message include it.