SQLiteException: Unable to open the database file - sqlite

I'm new to windows mobile programming and I'm trying to create a Windows Mobile 6 application using sqlite. Write now I have built a dummy test application where I try to read the contents of a an sqlite table.
The problem is that I keep receiving SQLiteException: Unable to open the database file.
My code is below:
using (var cn = new SQLiteConnection(#"Data Source=C:myfirsttest.s3db;"))
{
try
{
//Connect to SQLite database
cn.Open();
//Create the SQL Command
var cmd = new SQLiteCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT * FROM MyTable";
//Retrieve the records using SQLiteDataReader
var dr = cmd.ExecuteReader();
while (dr.Read())
{
//display records
var id = dr["ID"].ToString();
}
}
catch(Exception ex)
{
//display any exeptions
var except = ex.Message;
}
finally
{
cn.Close();
}
}
Can anyone help me please with that? Or suggest a tutorial where I can find how to setup sqlite in a windows mobile 6 project?

Windows CE (the base OS for WinMo) does not have drives nor does it have a concept of a working folder. This means that all paths must be fully qualified. You probably want something like:
new SQLiteConnection(#"Data Source=\myfirsttest.s3db;")
or
new SQLiteConnection(#"Data Source=\[my app path]\myfirsttest.s3db;")

Related

How can I get the current user from Sqlconnection

I am trying to determine what user my application is using to authenticate to my database, is there a way that I can get the user that is being used to execute the sql code?
string connection = WebConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = new SqlCommand();
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.CommandText = "MySPName";
adapter.SelectCommand.Connection = conn;
using (DataSet ds = new DataSet())
{
try
{
adapter.SelectCommand.Connection.Open();
logULS("Connection Open");
//Want to log the user that has the connection open...
adapter.Fill(ds);
adapter.SelectCommand.Connection.Close();
}
catch (Exception ex)
{
logULS(ex.ToString());
}
}
}
Try this:
SELECT CURRENT_USER;
GO
The above returns the name of the current user. Check here
To see current users connected you could use sp_who
sp_who [ [ #loginame = ] 'login' | session ID | 'ACTIVE' ]
Execute following command against database
sp_who2
it lists all open connections including logins and host names.

Monotouch and SQLite

I have a SQLite database with one table for cities name now I want to include this database to my monotouch project, connect to this database and select to this table. But I can find any tutorial to do this.
I don't new to create the database or create a new record. I just need to read the table.
Can anyone explain me how can I connect to my sqlite database an make a select.
Thanks in advance.
UPDATE
using(var connection = new SqliteConnection ("Data Source=zurfers.sqlite"))
{
using (var cmd = connection.CreateCommand()) {
connection.Open ();
cmd.CommandText = "SELECT * FROM City";
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
wordCollection = (string[])reader ["Name"];
}
}
}
}
include your DB file in your MonoTouch project and mark it as content.
using(var connection = new SqliteConnection ("Data Source=MyDatabase.sqlite"))
{
using (var cmd = connection.CreateCommand()) {
connection.Open ();
cmd.CommandText = "this is my query";
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
code = (string)reader ["ColumnName"];
}
}
}
}

Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I am trying to upload some excel file data in my application. From my local system (Windows 7) my code is working fine. But after hosting in server (2003), when I am trying to upload a file (.xlsx) I am getting an error - System.InvalidOperationException: The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
My code :
try
{
string connectionString = "";
if (fuUpload.HasFile)
{
string fileName = "_uploadTemp";
string fileExtension = Path.GetExtension(fuUpload.PostedFile.FileName);
string fileLocation = HttpContext.Current.Server.MapPath("~/FileUpload/" + fileName + fileExtension);
fuUpload.SaveAs(fileLocation);
lbl1.Text = "File Saved";
//Check whether file extension is xls or xslx
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
lbCon.Text = connectionString;
// Create OleDB Connection and OleDb Command
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
lbl2.Text = "Connection open";
//DataSet dtExcelSheetName=con.GetOleDbSchemaTable(OleDbDataAdapter.DefaultSourceTableName,null);
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
// dtExcelRecords = RemoveDuplicate(dtExcelRecords, "nOdc_Wwid");
con.Close();
lbl3.Text = "Connection Closed";
DataTable dttemp = new DataTable();
dttemp.Columns.Add("sOdc_People_Name", typeof(string));
dttemp.Columns.Add("vEmailId", typeof(string));
dttemp.Columns.Add("nOdc_Wwid", typeof(int));
dttemp.Columns.Add("Vpnaccess", typeof(string));//
dttemp.Columns.Add("Details", typeof(string));
for (int i = 0; i < dtExcelRecords.Rows.Count; i++)
{
dttemp.Rows.Add(dtExcelRecords.Rows[i][0].ToString(), dtExcelRecords.Rows[i][1].ToString(),
dtExcelRecords.Rows[i][2].ToString(), dtExcelRecords.Rows[i][3].ToString(), dtExcelRecords.Rows[i][4].ToString());
}
Session.Add("dtTemp", dttemp);//Created temp session to store the excel data
lbl4.Text = "Data added to temp table";
if (dttemp.Rows.Count <= 0)
{
gvMain.DataSource = mailutility.GetTempDataSetX("sOdc_People_Name", "vEmailId", "nOdc_Wwid", "Vpnaccess", "Details");
gvMain.DataBind();
gvMain.Rows[0].Visible = false;
}
else
{
gvMain.DataSource = dttemp;
gvMain.DataBind();
lnkConfirm.Visible = true;
lnkCancelC.Visible = true;
pnlLegend.Visible = true;
pnlLagendText.Visible = true;
mpX.Show();
lbl5.Text = "Grid binded";
foreach (GridViewRow gvr in gvMain.Rows)
{
CheckBox chkSelect = gvMain.Rows[gvr.RowIndex].Cells[0].FindControl("chkSelect") as CheckBox;
Label lblNameX = gvMain.Rows[gvr.RowIndex].Cells[1].FindControl("lblNameX") as Label;
Label lblEmailidX = gvMain.Rows[gvr.RowIndex].Cells[2].FindControl("lblEmailidX") as Label;
Label lblWwIdX = gvMain.Rows[gvr.RowIndex].Cells[3].FindControl("lblWwIdX") as Label;
if (lblNameX.Text != "" && IsValidEmail(lblEmailidX.Text) == true && ValidWWId(lblWwIdX.Text) == true)
{
chkSelect.Checked = true;
}
else
{
chkSelect.Checked = false;
chkSelect.Enabled = false;
gvr.BackColor = System.Drawing.Color.Yellow;
}
//Check for duplicate WWID
for (int i = 0; i < dttemp.Rows.Count; i++)
{
if (i != gvr.RowIndex)
{
if (dttemp.Rows[i]["nOdc_Wwid"].ToString() == lblWwIdX.Text)
{
chkSelect.Checked = false;
chkSelect.Enabled = false;
gvr.BackColor = System.Drawing.Color.Yellow;
}
}
}
}
}
}
}
catch (Exception es)
{
lbException.Text = es.ToString();
}
Please some one help me.
Gulrej
1.Try to download this from here: http://www.microsoft.com/en-us/download/confirmation.aspx?id=23734
2.Go to Visual Studio click add data source, follow the wizard.
This is the same problem I had before and followed steps from here:
http://social.msdn.microsoft.com/Forums/en-US/vstsdb/thread/1d5c04c7-157f-4955-a14b-41d912d50a64
You need to install the x86 version if the target machine is 32 bit or the x64 version if the target machine is 64 bit and your application is built with configuration Any CPU.
The first thing you need to check is your build configuration of your application.
If you have built your project under x86 platform, then in order to
resolve you issue you should install the following packages on your
machine:
In order to use the 'Microsoft.ACE.OLEDB.12.0' provider you must
install the Microsoft Access Database Engine 2010 Redistributable
first, this installation is available at:
http://www.microsoft.com/download/en/details.aspx?id=13255 .
After the installation has complete, try running you application, if this
solves the issue great, if not, continue to step 2.
This next step is an unexplained workaround, which works for Office
2010, even though it is the Data Connectivity Components of Office 2007. I am not quite sure why this works, but it does and this has been proven to work in almost all cases. You need to install the 2007 Office System Driver: Data Connectivity Components, this installation is available at:
http://www.microsoft.com/download/en/confirmation.aspx?id=23734 .
After this installation is complete, try running your application, this should resolve the issue.
If you are trying to run an application built under x64 or AnyCPU
platform, I would recommend first validating that it runs as expected
under the x86 platform. In the event that it does not run under that
x86 platform, perform the steps in the first part and validate that
it runs as expected.
I did read that the MS Access drivers including the OLEDB Database
driver works only under the x86 platform and is incompatible under
the x64 or AnyCPU platform. But this appears to be untrue. I
validated my application was running when building x86, then I
installed the Access Database Engine using the passive flag.
First download the file locally You can download the installation
here: http://www.microsoft.com/en-us/download/details.aspx?id=13255
Installing using the command prompt with the '/passive' flag. In
the command prompt run the following command:
'AccessDatabaseEngine_x64.exe /passive'
After these 2 steps I managed to run my application after building in
x64 or AnyCPU build configuration. This appeared to solve my issue.
Note: The order of the steps seems to make a difference, so please follow accordingly.

Not able to insert update delete

I'm using Asp.net c# and MYSql as back-end. I'm updating a table,but table is not updating.There are only 3 columns in the table.
There is no exception when I'm executing the command object. But this returns 0 value from cmd.ExecuteNonQuery().
I debugged this and found cmd.Parameters are full with values. and if i manually run the update command in mysql it works fine.
the table is as follow
column -- Datatype
ShortText -- varchar
title -- varchar
id -- int
Please guide me...
int retVal = 0;
string shortText = ((TextBox)fmvwShortText.FindControl("txtShortText")).Text.Trim();
try
{
int id = Convert.ToInt32(((Label)fmvwShortText.FindControl("lblShrtTextID")).Text);
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.AppSettings["conn"]);
cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE temp_posts SET ShortText=#shrtText WHERE id=#id AND Title=#title";
cmd.Parameters.Add("#shrtText", MySqlDbType.VarChar).Value = shortText;
cmd.Parameters.Add("#title", MySqlDbType.VarChar).Value =Session["EditTitle"].ToString();
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = id;
con.Open();
retVal = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception e) { }
return retVal;
Is it possibly a casing issue with your Title parameter? I notice you are only updating if the ID & Title match exactly?
Also as a general rule of thumb, when using objects which implement IDisposable you should wrap them with a using statement, this will make sure your objects are always disposed (even on the result of an error)
using (var con = new MySqlConnection(...))
{
using (var cmd = new MySqlCommand(...))
{
....
}
}
First of all thank you every one who kept looking and tried their best to sort out this problem with me..
Finally got the solution.
In my code I used # in cmd.CommandText and in parameters.
But when I replace this # with ? both in cmd.CommandText and in parameters and used the cmd.ExecuteScalar(); this worked.
Actually Parameter names depend on the provider. When using the provider for
SQL Server, it should start with # (e.g. #param1). For Oracle
provider, it should start with a colon (...for e.g. aram1. For
OleDb provider, just a question mark (?) would work
Thank you everyone to contribute your best... many thanks
But i'm still left with a question that ExecuteScalar() is updating the records in the database? I am with no answer... looking for this.
Try this nt sure about code formating coz currently am not using ide frmwrk
int retVal = 0;
string shortText = ((TextBox)fmvwShortText.FindControl("txtShortText")).Text.Trim();
try
{
int id = Convert.ToInt32(((Label)fmvwShortText.FindControl("lblShrtTextID")).Text);
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.AppSettings["conn"]);
cmd = new MySqlCommand("UPDATE temp_posts SET ShortText='"+shortText+"' WHERE id='"+id+"' AND Title='"+Session["EditTitle"].ToString()+"'",con);
con.Open();
retVal = cmd.ExecuteNonQuery();
con.Close();
return retVal;
}
catch (Exception e) { }

Connecting an ASP.NET MVC application to MySQL

How can I point my ASP.NET MVC application to a MySQL database?
Once you download the MySQL ADO.NET Connector it's a simple matter of referencing the assembly in your project and writing the queries, the same way you would do in any other application, nothing specific MVC:
using (var connection = new MySqlConnection(ConnectionString))
using (var cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT name FROM foo;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string name = reader.GetString(reader.GetOrdinal("name"));
// TODO: do something with the name ...
}
}
}

Resources