wpf 从文本框写入 sql server 2012 时,System.Data.dll 中发生类型为“System.InvalidOperationException”的未处理异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21305585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll While writing from textbox to sql server 2012
提问by
Trying my first WPF textbox to SQL express connection. I am receiving a An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dllWhile using sql 2012 express trying to write to a table called
尝试我的第一个 WPF 文本框到 SQL express 连接。我收到了An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dllWhile using sql 2012 express 试图写入名为的表
EVUSERS
EV用户
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
这是我试图将数据从 taxtbox 插入的表的图像。Employee.dbo.EVUSERS
EDITScreenshot
编辑截图
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.
我不知道为什么 open() 会出错;是连接字符串吗?或我正在使用的命令?该表确实存在。


采纳答案by Nagaraj S
MSDNsays
MSDN说
- Cannot open a connection without specifying a data source or server. or
- The connection is already open.
- 不指定数据源或服务器就无法打开连接。或者
- 连接已经打开。
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();
}
回答by Altair
You have two backslashes in the data source in your connection string, but have started the string with @ so do not need to escape the backslash.
您的连接字符串的数据源中有两个反斜杠,但字符串以 @ 开头,因此不需要对反斜杠进行转义。

