【发布时间】:2018-02-07 16:23:30
【问题描述】:
在我的程序中,我有两个文本输入字段(以 Windows 形式)和一个用于将这些值添加/保存到 DB 表中的按钮。问题是,一旦我单击按钮,它就不会将输入插入数据库,而是显示我在下面附加的错误图像。
我的程序有什么问题?
我的工作代码:
public partial class Form1 : Form
{
//original Connection string is exactly the following:
//Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\Sanad Al Nahaj\Documents\thesaurus.mdf";Integrated Security=True;Connect Timeout=30
SqlConnection conn = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\Sanad Al Nahaj\Documents\thesaurus.mdf;Integrated Security = True; Connect Timeout = 30");
public Form1()
{
InitializeComponent();
}
//Save button
private void button1_Click(object sender, EventArgs e)
{
conn.Open();//error pops up here after clicking the button
SqlCommand command = conn.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "insert into Table values('"+wordbox.Text+"','"+synonymbox.Text+"')";
command.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Word and Synonym added!");
}
private void display_Click(object sender, EventArgs e)
{
//implement
}
}
错误:
数据库如下:
更新:
我对Using模式的修改(参考CDove的回答):
var command = new SqlCommand();
using (command = new SqlCommand(
"insert into......)
))
【问题讨论】:
-
所述文件已附加
-
我想我看到了一个问题:您没有正确处理连接。将连接作为类比例变量保持打开的整个模式是一个坏主意。创建。采用。处置。这是处理一次性物品的唯一方法 (docs.microsoft.com/en-us/dotnet/csharp/language-reference/…)。不要担心性能。 SQLConenction 本身可能会做一些连接池。最后,无故障运行程序优先。
-
您能否尝试在您的 web.config 文件中执行:
,然后重试。 -
Eray Balkanli,你的意思是在我的 web.config 文件中吗?在这种情况下,它应该在
标签内吗? -
我的意思是相关应用程序的 web.config 文件。相信你会在Visual Studio的项目下看到它
标签: c# sql visual-studio sqlconnection