Reputation: 24
Hi there im new to C# and SQL. But my problem is with SQL im trying to conect to a Database i created on visual studio 2010. it trhows me the exception of cannot convert vachar to float. Here is the code.
private void execute()
{
///Here we atempt to connect to the local DB
System.Data.SqlClient.SqlConnection SqlConnection1 = new
System.Data.SqlClient.SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated
Security=True;User Instance=True");
SqlConnection1.Open();
System.Data.SqlClient.SqlTransaction tx = SqlConnection1.BeginTransaction();
System.Data.SqlClient.SqlCommand cmd = SqlConnection1.CreateCommand();
cmd.Transaction = tx;
///Here we try to operate on the Local DB
try
{
cmd.CommandText = "INSERT INTO EmployeeInfo(EmployeeSalary,EmployeePhone,EmployeeDeskPhone,EmployeeSSN,EmployeeEmergencyContactName,EmployeeEmergencyContactPhone,EmployeeFirstName,EmployeeLastName) VALUES
(@_employeeSalary,'@_employeePhone','@_employeeDeskPhone','@_employeeSSN','@_employeeEmergencyContactName','@_employeeEmergencyContactPhone','@_employeeFirstName','@_employeLastName')";
cmd.Parameters.AddWithValue("@_employeeSalary", _employeeSalary);
cmd.Parameters.AddWithValue("@_employeePhone", _employeePhone);
cmd.Parameters.AddWithValue("@_employeeDeskPhone", _employeeDeskPhone);
cmd.Parameters.AddWithValue("@_employeeSSN", _employeeSSN);
cmd.Parameters.AddWithValue("@_employeeEmergencyContactName",
_employeeEmergencyContactName);
cmd.Parameters.AddWithValue("@_employeeEmergencyContactPhone",
_employeeEmergencyContactPhone);
cmd.Parameters.AddWithValue("@_employeeFirstName", _employeeFirstName);
cmd.Parameters.AddWithValue("@_employeeLastName", _employeeLastName);
cmd.ExecuteNonQuery();
tx.Commit();
}
///If unsuccesful we rollback changes
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
tx.Rollback();
Console.WriteLine("**** There was Trouble Houston, with the Insert****");
}
///Thhis piee of code always executes
finally
{
SqlConnection1.Close();
Console.WriteLine("***** if theres no trouble before this, then It succesfully added the record to the database*****");
}
}
the variable emplyeeSalary is set to float and is the only one so i don get whjy it trhows that message. Please any help would be deeply apreciated.
Upvotes: 0
Views: 104
Reputation: 20494
Your problem is quite simple, you've placed the command parameters inside single quotes for some reason. Change them to the following:
cmd.CommandText = @"INSERT INTO
EmployeeInfo( EmployeeSalary ,EmployeePhone, EmployeeDeskPhone, EmployeeSSN,
EmployeeEmergencyContactName, EmployeeEmergencyContactPhone, EmployeeFirstName,
EmployeeLastName) VALUES
(@_employeeSalary,@_employeePhone,@_employeeDeskPhone,@_employeeSSN,
@_employeeEmergencyContactName,@_employeeEmergencyContactPhone,
@_employeeFirstName, @_employeLastName)";
Upvotes: 3