Trying my first WPF textbox to SQL express connection. I am receiving a An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
While using sql 2012 express trying to write to a table called
EVUSERS
on database
Employee
The error comes at
connection.Open();
Here is my code.
void saveData()
{
try
{
string firstName = FNameTextbox.Text;
string connectionString = @"Data Source=.\\SQLEXPRESS; Database=Employee;Integrated Security=True;User Instance=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = " INSERT INTO EVUSERS (FName) VALUES (@FName)";
command.Parameters.AddWithValue("@FName", firstName);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Here is an image of the table I am trying to insert the data into from the taxtbox. Employee.dbo.EVUSERS
EDIT Screenshot
I have no idea why there is an error at the open(); Would it be the connections string? or the command I am using? The table definetely exists.
您的连接字符串中的数据源中有两个反斜杠,但是已使用@开头了字符串,因此不需要转义反斜杠。
MSDN says
So check your connection string
using (SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=Employee;Integrated Security=SSPI;"))
{
connection.Open();
SqlCommand command= connection.CreateCommand();
command.CommandText = " INSERT INTO EVUSERS (FName) VALUES (@FName)";
command.Parameters.AddWithValue("@FName", firstName);
command.ExecuteNonQuery();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.