我目前正在为我的控制台应用程序使用这个 SQLite 库:http://system.data.sqlite.org/index.html/doc/trunk/www/index.wiki - 到目前为止,SELECT 查询没问题,但是执行此 INSERT 操作给我带来了问题,我还没有找到解决方案。
我猜代码可以重写,但我看不出如何重写?
代码
public string NewChannel(string _channel)
{
SQLiteConnection m_dbConnection = new SQLiteConnection(m_connection);
using (var cmd = m_dbConnection.CreateCommand())
{
m_dbConnection.Open();
cmd.CommandText = "INSERT INTO channels (name) VALUES (@name)";
cmd.Parameters.AddWithValue("@name", _channel);
try
{
int result = cmd.ExecuteNonQuery();
return "New channel added: " + _channel;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
}
}
错误
SQLite error (10): delayed 1375ms for lock/sharing conflict SQLite
error (14): os_win.c:34909: (5) winOpen(c:\db.sqlite-journal) - Access is denied. SQLite error (14): os_win.c:34909: (2)
winOpen(c:\db.sqlite-journal) - The system cannot find the file
specified. SQLite error (14): cannot open file at line 34917 of
[118a3b3569] SQLite error (14): statement aborts at 7: [INSERT INTO channels (name) VALUES (@name)]
最佳答案
特定的错误代码表示如下:
Error Code 14: SQL Lite Database File Can't be Opened.
以管理员身份运行 Visual Studio 的原因是您提升了读写权限。这并不是说它实际上是在创建一个新文件,而是它可能正在读取或写入数据到该文件。
除非已明确定义权限,否则基于可能会根据给定角色限制的特定权限。
正如我在上面提到的,根 C:
需要 高级用户或更高级别 才能在根上写入 数据。当您的数据库尝试附加时,它被认为是写入,它可能无法执行。
- 解决方案一:明确定义应用程序/用户的权限以避免出现问题。
- 解决方案二:在它尝试访问数据文件之前写一个检查以确保适当的权限。
这种检查的一个例子:
public ValidFolderPermission(string filePath)
{
if(File.Exist(filePath))
{
// Open Stream and Read.
using (FileStream fs = File.Open(filePath, FileMode.Open))
{
byte[] data = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}
}
在这种情况下,如果它实际上打开了该路径中的文件,那么您就有了正确的访问权限。如果没有,则您没有权限。
重要:要真正进行测试,您应该使用 try
和 catch
,甚至可能使用 boolean returns
以确保它确实正确处理在写入数据库之前。
您甚至可以像这样检查用户权限级别:
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal role = new WindowsPrincipal(user);
if(role.IsInRole(WindowsBuiltInRole.Administrator)
{
// Do Something
}
else
{
// Do Something Else
}
这是一种通用方法,但有更好更简洁的方法可以测试操作系统的用户访问控制功能、用户帐户的空值等,以及处理您可能遇到的其他问题。
希望这能为您指明正确的方向。
关于c# - System.Data.SQLite 锁/共享冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17076628/