I just started working on a sample application that only calls some tables on my SQLite database, and I have managed to solve other issues that have happened except this one.
Although I have searched for this, none of the suggested solutions for the connectionstring, permission issues and etc seem to be valid and working for me. For the permissions, I added the Everyone user with full control, and I still get the same error.
Below is the code that I am trying to execute:
// calling function
void getRecords2()
{
MySqlLite.DataClass ss = new MySqlLite.DataClass();
DataTable dt = ss.selectQuery("select * from english_words");
}
// the SQLite class that execute the code
using System.Data;
using System.Data.SQLite;
namespace MySqlLite
{
class DataClass
{
private SQLiteConnection sqlite;
public DataClass()
{
//This part killed me in the beginning. I was specifying "DataSource"
//instead of "Data Source"
sqlite = new SQLiteConnection(#"Data Source=C:\testwork\db\MrPick.sqlite3.db;Version=3;FailIfMissing=True");
}
public DataTable selectQuery(string query)
{
SQLiteDataAdapter ad;
DataTable dt = new DataTable();
try
{
SQLiteCommand cmd;
sqlite.Open(); //Initiate connection to the db
cmd = sqlite.CreateCommand();
cmd.CommandText = query; //set the passed query
ad = new SQLiteDataAdapter(cmd);
ad.Fill(dt); //fill the datasource
cmd.Dispose();
sqlite.Dispose();
}
catch (SQLiteException ex)
{
//Add your exception code here.
}
sqlite.Close();
return dt;
}
}
}
Note: I used the following assembly:
ADO.NET SQLite Data Provider
Version 1.0.82.0 September 3, 2012
Using SQLite 3.7.14
Originally written by Robert Simpson
Released to the public domain, use at your own risk!
Official provider website: http://system.data.sqlite.org/
I really appreciate your help on this.
Per your comment, you're getting a "Unable to open database file" error because you're pointing the code at a file that doesn't exist.
A "Table not found" error means it found the database, but not the table you were looking for. On the other hand, "Unable to open database file" means that it couldn't even find the database, and didn't even bother looking for a table. You're much closer to it working correctly when you're getting "Table not found".
You should change the path back to match the file on disk, then use a tool like the Firefox SQLite Manager to confirm that the english_words table does exist in your database.
If it doesn't, you should create it with that tool, and if it does, you should post another question here about the "Table not found" error.
Hopefully that helps.
When I ran into this error I had to set parseViaFramework in the SQLiteConnection constructor to true.
SQLiteConnection connection = new SQLiteConnection(connectionString, true);
connection.Open();
I was facing same issue on the shared hosting server,
My C# code was able to read data from SQLIte db file.
But while add / update data it was throwing Error "unable to open database"
I tried many options suggested on stackoverflow
But after referring
https://stackoverflow.com/a/17780808/2021073
and
https://www.sqlite.org/pragma.html#pragma_journal_mode
I tried adding journal mode=Off; to the Connection string
and it worked for me
sample code
SQLiteConnection connection = new SQLiteConnection("Data Source=G:\dbfolder\sqlite3.db;Version=3;Mode=ReadWrite;journal mode=Off;", true);
Related
I have a c# winform project that supposes to save data to SQLite database, I've already used the dll properly and it runs without error, but I get an exception when trigger the method with buttonClick event
here the exception i got : Keyword not supported :'version'.
this the connection string:
"Data Source = Diary.db;Version = 3;New = False;Compress = True;";
and this the complete method :
private void AddToDbaseSQL3()
{
try{
string query = "insert into Diary(title,date,mood,wheater,content)
values('"+TitleTextbox.Text+"','"
+dateTimePicker.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','"
+MoodCombobox.SelectedItem+"','"
+WheaterCombobox.SelectedItem+"','"
+ContentTextbox.Text+"');";;
SqlConnection connect2 = new SqlConnection(connection2);
SqlCommand cmd = new SqlCommand(query,connect2);
SqlDataReader read;
connect2.Open();
read = cmd.ExecuteReader();
while(read.Read())
{
}
MessageBox.Show("created");
TitleTextbox.Text = "Title";
TitleTextbox.ForeColor = SystemColors.ControlLight;
ContentTextbox.Clear();
connect2.Close();
}catch(Exception e){
MessageBox.Show(e.Message);
}
}
I've looked to this link:
Keyword not supported: 'version'
and it said to change SqlConnection to SQLiteConnection but it ended with an error, can you tell what's is the right connection string ? or there is something wrong from my code/method? please tell me, thank you, I'm sorry because it's my first time using the SQLite
SqlConnection from System.Data.SqlClient is for SQL Server.
You need an dedicated SQLite ADO.NET provider.
You can found the System.Data.SQLite provider from SQLite team here:
https://system.data.sqlite.org
Or you can use any libre or commercial provider.
You can also use the free and open-source SQLite ODBC driver that works fine and allow to use VS Visual Designers to create strongly typed ADO.NET DataSets, in addition to the use of OdbcConnection, OdbcCommand and so on:
http://www.ch-werner.de/sqliteodbc
C# Reading data from existing SQLite database
I am writing a Windows Forms application that needs to query 2 fields from a MAS-90 database. For this we use the MAS 90 32-bit ODBC Driver by ProvideX called SOTAMAS90. Here is the code I use to retrieve a DataTable from the MAS-90 database.
public static DataTable getDatatable(string qry)
{
DataTable dt = new DataTable();
using (OdbcConnection conn = new OdbcConnection(GetSQLConnection()))
{
try
{
OdbcCommand cmd = new OdbcCommand(qry, conn);
cmd.CommandType = CommandType.Text;
conn.Open();
OdbcDataAdapter adpt = new OdbcDataAdapter(cmd);
adpt.Fill(dt);
cmd.Dispose();
conn.Close();
conn.Dispose();
}
catch (OdbcException e) { conn.Close(); }
catch (AccessViolationException ae) { conn.Close(); }
catch (UnauthorizedAccessException ue) { conn.Close(); }
}
return dt;
}
On line adpt.Fill(dt) I get the following exception:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
This was working just fine yesterday. Today Visual Studio is telling me that this is an Unhandled AccessViolationException even though you can clearly see the try/catches. I had to add <legacyCorruptedStateExceptionsPolicy enabled="true"/> to my config file just for the exception to be caught in the try/catch.
The other strange thing is I am able to connect to the database and run the same exact query (which is just selecting 2 fields from a table) using the ODBC Query Tool by Jaime De Los Hoyos M. (Available here)
Any help at resolving this issue is greatly appreciated. Please let me know if you need additional information.
I also wanted to add that I have tried:
Targeting x86 in my app as the Driver is 32-bit
Giving permissions to the directory where the database is stored
Restarting PC
Changing query to add parameters with cmd.Parameters.AddWithValue("#PARAM", "Value")
I was able to resolve my issue. The database was stored on a server to which my PC had a mapped drive to. For whatever reason, the mapping broke for the MAS 90 32-bit ODBC Driver. This was strange because I was still able to access the network drive's files via File Explorer and I was also able to query the table via the ODBC query tool I mentioned (which uses the same ODBC driver). I discovered this when I wanted to change the Database Directory field (seen below) and it kept telling me the path was invalid or inaccessible (even though it was accessing it for the ODBC query tool).
Anyway, I remapped the network drive, then deleted and recreated the SOTAMAS90 DSN and it worked again.
I have an asp.net C# application (.net 4.0) connected to SQL Server 2012 using ADO.Net and am encountering an error which says:
[InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
I very well know what a DataReader is but, my problem is getting this error in below conditions:
I have not at all used any DataReader in my application, I have only
used DataAdapters everywhere. The code works fine while running in
local environment and there is no errors.
Application works fine even after deployment in IIS7 when used by a
single user.
The error only occurs when multiple users starts using the website hosted in IIS7.
Kindly help, I am also doubting for any problems with my hosting in IIS7
After a lot of trial and error, finally I found out that it's a problem with SqlConnections. What I used to do was open a connection at the instantiation of my DAL layer object. So, whenever two methods from the same DAL object called together, it used to throw the error.
I solved it by opening and closing a connection in every call to the database. Now it all works fine. This also allows max number of users to use the application at a time. Below is my code sample from DAL:-
DataTable dt = new DataTable();
try
{
using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString()))
{
if (sqlcon.State == ConnectionState.Closed)
sqlcon.Open();
SqlCommand sqlCommand = new SqlCommand
{
Connection = sqlcon,
CommandType = CommandType.StoredProcedure,
CommandText = "MyStoredProc"
};
sqlCommand.Parameters.AddWithValue("#Parameter1", Parameter1);
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand))
{
adapter.Fill(dt);
}
}
return dt;
}
catch (Exception exp)
{
LogHelper.LogError(string.Concat("Exception Details: ", ExceptionFormatter.WriteExceptionDetail(exp)));
throw exp;
}
finally
{
dt.Dispose();
}
Please post a better way of doing it if you know any, thank you.
I am using SQLite.NET with C#[ visual studio 2008] and added the 'System.Data.SQLite.dll' as reference. The following code works with Windows Application for fetching data from my database file into a datagrid.
private void SetConnection()
{
sql_con = new SQLiteConnection("Data Source=emp.db;Version=3;");
}
public DataTable LoadData()
{
SetConnection();
sql_con.Open();
sql_cmd = sql_con.CreateCommand();
string CommandText = "select * from employeedetails";
transaction=sql_con.BeginTransaction();
DA = new SQLiteDataAdapter(CommandText, sql_con);
DS.Reset();
DA.Fill(DS);
DT = DS.Tables[0];
transaction.Commit();
sql_con.Close();
return DT;
}
Invoking in:
private void Form1_Load(object sender, EventArgs e)
{
EmpTable obj = new EmpTable();
this.dataGridView1.DataSource = obj.LoadData();
}
The same code not working with C# 'Smart Device Application'. It shows an exception: no such table 'employeedetails'.
For Smart Device Application I have added the System.Data.SQLite.dll from "SQLite/CompactFramework" folder.
Please help me to resolve this.
Thanks in advance.
I'm not sure if this is what is causing your issue, but we've had issues in the past with mobile devices and sqlite where this solved it:
For an application using the compact framework, you need to include SQLite.Interop.xxx.DLL in your project (in addition to the regular System.Data.SQLite.DLL). Make sure you set the file to copy if newer or copy always.
Keep in mind that you can't set a reference to the interop dll. You must include it in the project by adding it as a file.
For more information check this website under the Distributing The SQLite Engine and ADO.NET Assembly section.
Thank You Guys,
I've resolved the Problem. As 'siyw' said, the problem was the application could not find the "db file".
For windows application,
The db file has to be located in debug folder where the .exe file is generated. So that, no need to specify the path of the DB file.
For Smart Device Application,
The DB file will be generated in the root folder of the device. If we bind the db file with exe means, it wont find it and it will create a new database in root folder.
To avoid that, while crating CAB file we have to create custom folder [ ex. DBfolder ] and put the db file in the folder.
Set the path in the connection String as,
sql_con = new SQLiteConnection("Data Source=DBfolder/emp.db;Version=3;");
Now, the db is found by the Application.
sql_con = new SQLiteConnection("Data Source=emp.db;Version=3;");
I think you need to specify the full path here, and make sure it's correct. If the path is to a non-existent file, it will create a new emp.db database file there instead. This new file will obviously be empty and without any tables, hence it would give a no such table 'employeedetails' exception such as you're getting if you query it.
I'm trying to read a Paradox 5 table into a dataset or simular data structure with the view to putting it into an SQL server 2005 table. I've trawled google and SO but with not much luck. I've tried ODBC:
public void ParadoxGet()
{
string ConnectionString = #"Driver={Microsoft Paradox Driver (*.db )};DriverID=538;Fil=Paradox 5.X;DefaultDir=C:\Data\;Dbq=C:\Data\;CollatingSequence=ASCII;";
DataSet ds = new DataSet();
ds = GetDataSetFromAdapter(ds, ConnectionString, "SELECT * FROM Growth");
foreach (String s in ds.Tables[0].Rows)
{
Console.WriteLine(s);
}
}
public DataSet GetDataSetFromAdapter(DataSet dataSet, string connectionString, string queryString)
{
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
OdbcDataAdapter adapter = new OdbcDataAdapter(queryString, connection);
connection.Open();
adapter.Fill(dataSet);
connection.Close();
}
return dataSet;
}
This just return the error
ERROR [HY000] [Microsoft][ODBC Paradox Driver] External table is not in the expected format.
I've also tired OELDB (Jet 4.0) but get the same External table is not in the expected format error.
I have the DB file and the PX (of the Growth table) in the Data folder... Any help would be much appriciated.
I've had the same error. It appeared when I started my C# project on Win2008 64 (previos OS was Win2003 32). Also I found out that it worked fine in console apps and gave different errors in winforms. It seems that problem comes from the specifics of 32 ODBC driver working on 64-bit systems.
My solution was:
// Program.cs
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// it is important to open paradox connection before creating
// the first form in the project
if (!Data.OpenParadoxDatabase())
return;
Application.Run(new MainForm());
}
The connectionstring is common:
string connStr = #"Driver={{Microsoft Paradox Driver (*.db )}};DriverID=538;
Fil=Paradox 7.X;DefaultDir=C:\\DB;Dbq=C:\\DB;
CollatingSequence=ASCII;";
After opening connection you may close it in any place after creating first Form (if you need to keep DB closed most of time), for example:
private void MainForm_Load(object sender, EventArgs e)
{
Data.CloseParadoxDatabase();
}
After doing that you may open and close connection every time you want during execution of your application and you willn't get any exceptions.
Maybe this will help you out,
http://support.microsoft.com/support/kb/articles/Q237/9/94.ASP?LN=EN-US&SD=SO&FR=1
http://support.microsoft.com/support/kb/articles/Q230/1/26.ASP
It appears that the latest version of the Microsoft Jet Database Engine
(JDE) does not fully support Paradox unless the Borland Database Engine
(BDE) is also installed.
Try to Run all The Applications with the "Run As Administrator" privileges especially run the VS.NET with "Run As Administrator "... and I am sure your problem get solved
This isn't an answer, but more of a question: any particular reason you're trying to use C# to do the data manipulation as opposed to using SQL Server tools to load the data directly? Something like DTS or SSIS would seem like a better tool for the job.
Thanks, I'll give that a try. I wanted to use C# so I can put it on some web pages without the extra set of putting it in SQL server.