I'm working on a group project and one of the other group participants wrote one of the page's backend logic. I ran his code and to my surprise no errors, but also the data is not inserted into the database. I tried using a try-catch
to force an exception out if there is one, but nothing. Any ideas to what might cause this?
private async Task Adding_Com(string company_ID, string company_Name, string address, string website, string contact_No, string logo)
{
string Query = "INSERT INTO Company (Comp_ID, CompanyLogo, Comp_TelNum, Comp_Name, Comp_Address, Comp_Website) "
"VALUES (@ComId, @logo, @con, @ComName, @address, @site)";
await Task.Run(() =>
{
using (var conn = new SqlConnection(connString))
using (var action = new SqlCommand(Query, conn))
{
action.Parameters.Add("@ComId", SqlDbType.VarChar, 25).Value = company_ID;
action.Parameters.Add("@logo", SqlDbType.VarChar, 225).Value = logo;
action.Parameters.Add("@con", SqlDbType.VarChar, 45).Value = contact_No;
action.Parameters.Add("@ComName", SqlDbType.VarChar, 55).Value = company_Name;
action.Parameters.Add("@address", SqlDbType.VarChar, 55).Value = address;
action.Parameters.Add("@site", SqlDbType.VarChar, 55).Value = website;
conn.OpenAsync();
try
{
action.ExecuteNonQueryAsync();
_ = MessageBox.Show("Company Has Been Registered");
}
catch (SqlException ex)
{
_ = MessageBox.Show(ex.Message);
}
}
});
}
The SQL table
CREATE TABLE Company
(
Comp_ID VARCHAR(25) PRIMARY KEY NOT NULL ,
CompanyLogo VARCHAR(255) NOT NULL,
Comp_TelNum VARCHAR(45) NOT NULL,
Comp_Name VARCHAR(55) NOT NULL,
Comp_Address VARCHAR(55) NOT NULL,
Comp_Website VARCHAR(55) NOT NULL
);
CodePudding user response:
Your problem is that you should await the OpenAsync
and the ExecuteNonQueryAsync
because if you don't, race conditions could happen and you will see nothing happens.
Your code should look similar to this:
using (var conn = new SqlConnection(connString))
using (var action = new SqlCommand(Query, conn))
{
action.Parameters.Add("@ComId", SqlDbType.VarChar, 25).Value = company_ID;
action.Parameters.Add("@logo", SqlDbType.VarChar, 225).Value = logo;
action.Parameters.Add("@con", SqlDbType.VarChar, 45).Value = contact_No;
action.Parameters.Add("@ComName", SqlDbType.VarChar, 55).Value = company_Name;
action.Parameters.Add("@address", SqlDbType.VarChar, 55).Value = address;
action.Parameters.Add("@site", SqlDbType.VarChar, 55).Value = website;
// We wait to the connection to be opened to make sure we do not work with a closed connection
await conn.OpenAsync();
try
{
// We wait the command to finish before claiming the data was inserted.
await action.ExecuteNonQueryAsync();
_ = MessageBox.Show("Company Has Been Registered");
}
catch (SqlException ex)
{
_ = MessageBox.Show(ex.Message);
}
}