我有一个Winform程序,该程序具有很多与本地MDF数据库交互的SqlConnection函数。
这是我创建连接字符串的方式:
String dbPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Bot\DB\BotDB.mdf";
String con = String.Format("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"{0}\";Integrated Security=True;Connection Timeout=10;", dbPath);
return con;
这是我对数据库进行的许多调用之一:
public bool InsertNewUserToTable(String username)
{
using (SqlConnection con = new SqlConnection(DataBase.GetConString()))
{
con.Open();
String query = @"INSERT INTO dbo.Users(username) VALUES(@username);";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@username", username);
int count = cmd.ExecuteNonQuery();
con.Close();
return (count == 0) ? false : true;
}
}
}
我有更多类似的方法,可以从数据库中删除,更新和插入数据。
使用多线程的程序以这种方式访问数据库。
问题是有时我会崩溃(在发布模式下):
Problem signature:
Problem Event Name: CLR20r3
Problem Signature 01: Bot.exe
Problem Signature 02: 1.0.0.0
Problem Signature 03: 5cbce361
Problem Signature 04: System.Data
Problem Signature 05: 4.7.2623.0
Problem Signature 06: 5a1f67d8
Problem Signature 07: 1a55
Problem Signature 08: 5e
Problem Signature 09: System.Data.SqlClient.Sql
OS Version: 6.3.9600.2.0.0.272.7
Locale ID: 1033
Additional Information 1: 4e4b
Additional Information 2: 4e4be395a3a959f2a72f71ab9c9204ab
Additional Information 3: 783e
Additional Information 4: 783ea04fb900812a4241ad9aeb1b45b6
Read our privacy statement online:
http://go.microsoft.com/fwlink/?linkid=280262
If the online privacy statement is not available, please read our privacy statement offline:
C:\Windows\system32\en-US\erofflps.txt
我试图找到一种使用此信息查找特定异常的方法: https://stackoverflow.com/a/4053325/679099
但是我无法找到使我的应用程序崩溃的任何特定内容。
任何想法都可能是什么问题?我还想念其他东西吗?
答案 0 :(得分:0)
尝试定义一个私有SqlConnection并将此代码放在InitializeComponent();
下con = new SqlConnection(@"Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"{0}\";Integrated Security=True;Connection Timeout=10;User Instance=True;MultipleActiveResultSets=True;");
con.Open();
此连接适用于已打开的多个连接,因为您具有MARS = True;
然后对于SqlCommand,您只需要这样做:
SqlCommand cmd = new SqlCommand("query", con);
SqlConnection的最终代码必须如下所示:
private SqlConnection con;
public Form1()
{
InitializeComponent();
con = new SqlConnection(@"Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"{0}\";Integrated Security=True;Connection Timeout=10;User Instance=True;MultipleActiveResultSets=True;");
con.Open();
}