I'm having difficulty inserting a simple record to the database. I'm not getting any errors while saving it. Also, I can verify that it got inserted if I try to retrieve it while program is running. But as soon as I close the program and refresh the database, it doesn't appear in the database. I know this is a commit problem but not sure what exactly I'm missing here.
private void saveEmpBtn_Click(object sender, EventArgs e)
{
string aSQL = "INSERT INTO Employee(Id, Name, Type, Email, UTAId, Dept) VALUES (@Id, @Name, @Type, @Email, @UTAId, @Dept) ";
using (conn = new SqlConnection(connectionString))
{
conn.Open();
using (var tx = conn.BeginTransaction())
using (SqlCommand command = new SqlCommand(aSQL, conn))
{
command.Connection = conn;
command.Transaction = tx;
command.Parameters.AddWithValue("@Id", 3);
command.Parameters.AddWithValue("@Type", empTypCmbBx.SelectedItem.ToString());
command.Parameters.AddWithValue("@Name", nmTxtBx.Text);
command.Parameters.AddWithValue("@UTAId", utaIdTxtBx.Text);
command.Parameters.AddWithValue("@Email", emailTxtBx.Text);
command.Parameters.AddWithValue("@Dept", deptTxtBx.Text);
try
{
command.ExecuteNonQuery();
tx.Commit();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("Employee Saved Successfully");
}
}
Included few images of database script of the table. Schema definition and ID properties as well. Some questions: the example I followed had employee.mdf
and had only one table. In my case database name is RoomAllocationSystemDatabase
and table name is Employee
. Do I have to include schema as dot notation to access the table in the insert statement? I tried this. When I do, it says invalid object. Not sure if I need to include database name somewhere else.
CREATE TABLE [dbo].[Employee]
(
[Id] INT NOT NULL,
[Name] VARCHAR (50) NULL,
[Type] VARCHAR (50) NULL,
[Email] VARCHAR (50) NOT NULL,
[UTAId] VARCHAR (50) NULL,
[Dept] VARCHAR (50) NULL,
[Password] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Connection string logic while loading the form
connectionString = ConfigurationManager.ConnectionStrings["RoomAllocationSystem.Properties.Settings.RoomAllocationSystemDatabaseConnectionString"].ConnectionString;
Connection string in app.config
:
<connectionStrings>
<add name="RoomAllocationSystem.Properties.Settings.RoomAllocationSystemDatabaseConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\RoomAllocationSystemDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>