As already noticed by a few members, your code is bad and your logic is messed up. First off, you should
NOT append the values of your
TextBox
to your SQL statement as it could potentially leads you to
SQL Injection
attack. Here's an article that I wrote a while back the demonstrate how dangerous it is:
[
^]
Second, don't hard code your connection string and embed it in your C# code.
Connection String
should be put in your web.config file under connectionStrings element:
Creating a Connection String and Working with SQL Server LocalDB | Microsoft Docs[
^]
For example:
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=NoveltySystem;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
You can then reference your Connection String value via
ConfigurationManager
class like this:
string dbConnectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
Third, don't initialize your
SqlConnection
in
Page_Load
event since you are inserting data at
Button
's
Click
event.
Forth, make it a habit to put objects that eat resources such as
SqlConnection
,
SqlCommand
within a using block to ensure that objects will be properly disposed and after they are used.
Finally, I would recommend you to separate your code/logic for inserting data to database and keep them out from your Button click event for the ease of maintenance and separation of concerns.
Your code would now look something like this:
private void InsertRecord(string name, string language, string std, string author, string edition, string price, string stock){
string dbConnectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(dbConnectionString)) {
string sql = "INSERT INTO addBooks(BkName,BkLanguage,BkStd,BkAuthore,BkEditions,BkPrice,BkStocks) VALUES (@BookName,@BookLanguage,@BookStd,@BookAuthor,@BookEdition,@BookPrice,@BookStock)";
using (SqlCommand cmd = new SqlCommand(sql, connection)) {
connection.Open();
cmd.Parameters.AddWithValue("@BookName", name);
cmd.Parameters.AddWithValue("@BookLanguage", language);
cmd.Parameters.AddWithValue("@BookStd", std);
cmd.Parameters.AddWithValue("@BookAuthor", author);
cmd.Parameters.AddWithValue("@BookEdition", edition);
cmd.Parameters.AddWithValue("@BookPrice", price);
cmd.Parameters.AddWithValue("@BookStock", stock);
cmd.ExecuteNonQuery();
}
}
}
protected void addB_Click(object sender, EventArgs e){
InsertRecord(bname.Text,blang.Text,bstd.Text,bauthore.Text,bedition.Text, bprice.Text,bstocks);
}
Note: The may need to double check the
datatype
you used in your
SQL
Database
as we passing all parameters as
string
datatype
in this example. For example, if the
BkPrice
and
BkStocks
columns in your database is
decimal
and
integer
, then you need to change your C# code
datatype
as well.
Hope that helps!