I followed this tutorial to import my existing database http://wp.qmatteoq.com/import-an-already-existing-sqlite-database-in-a-windows-8-application/ After copying my DB to project files and setting build action as content,I am copying the database to isolated storage.Now when I try to update a value in the database,and view the change in my binded list box, Im not able to see the changes.When I use isolated storage explorer and view the DB,the values have changed in DB.But querying it doesnt return me the updated values.I am using the same connection string in both cases.
//copy DB from installation folder to isolated storage
private async Task CopyDatabase()
{
bool isDatabaseExisting = false;
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("sample.db");
isDatabaseExisting = true;
}
catch
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("sample.db");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
}
//update the value
dbConn = new SQLiteConnection(DB_PATH);
dbConn.Query<resources>(" update resources SET isFavorite = 'True' WHERE resourceId =" + rid);
}
// Query database to populate list box
string DB_PATH = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sample.db");
private SQLiteConnection dbConn;
dbConn = new SQLiteConnection(DB_PATH);
List<resources> retrievedpdf = dbConn.Query<resources>("select * from resources where categoryId=" + noid + " AND typeId=1" ).ToList<resources>();
pdflist.ItemsSource = retrievedpdf;
I am able to view changes in exploreer, but querying returns unmodified values.
I would like some changes in query that helps me a lot.
//Copy your database file From Installation folder to IsolatedStorage on App launching.
//Change your update query bu below query
int updateCount = dbConn.Execute("update resources SET isFavorite = 'True' WHERE resourceId =" + rid);
//Change your select Query
**Edits**
List<resources> retrievedpdf = dbConn.Table<resources>().ToList().Where(x=>x.categoryId.Equals(noid) && x.typeId.Equals(1)).ToList();
//Assign ListBox ItemSource to null before assign actual source
pdflist.ItemsSource = null;
pdflist.ItemsSource = retrievedpdf;
There was a problem with the query , I had been updating string "true" to a bool in a table..This is the correct query int updateCount = dbConn.Execute("update resources SET isFavorite = 1,modifiedTime = DATETIME('now') WHERE resourceId =" + rid);
Related
I am using Visual Studio 2017 with smo dll
and trying to remove a file from database files with the following procedure
public string RemoveFile(string fileName,string databaseName)
{
Server srv = new Server(servConn);
Database database = srv.Databases[databaseName];
if (database != null)
{
var file = LoadFiles(databaseName).Where(a => a.Name == fileName);
if (!file.Any())
{
SqlServerDisconnect();
return "File Doesn't Exist.kindly Enter Right File Name";
}
else
{
DataFile fileToRemove = file.FirstOrDefault();
database.FileGroups[fileToRemove.Parent.Name].Files.Remove(fileToRemove);
database.Alter();
return "File Removed Successfully";
}
}
}
I am not going to mention the code of servConn parameter and SqlServerDisconnect in order to abbreviate code that I have used in other places and I am sure that it works well.
When I remove a file that I take it's name from one of existing files' logical names
RemoveFile("File1",MyDataBase")
I get the message:
You cannot perform operation Remove on an object in state Existing.
How can I update the state of the file before removing it even though state field is read only and is my way in removing the file right?
You are using SMO however; For alternative way, If you can execute the SQL to do these operations. I would suggest to simply use TSQLs to remove file like :
ALTER DATABASE SchoolDb2012
REMOVE FILE schoolDataFile1;
GO
You can find detailed information here https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-database-transact-sql-file-and-filegroup-options?view=sql-server-2017
i updated my procedure to drop the file directly and not from it's file group
and the exception disappeared
public string RemoveFile(string fileName,string databaseName)
{
Server srv = new Server(servConn);
Database database = srv.Databases[databaseName];
if (database != null)
{
var file = LoadFiles(databaseName).Where(a => a.Name == fileName);
if (!file.Any())
{
SqlServerDisconnect();
return "File Doesn't Exist.kindly Enter Right File Name";
}
else
{
DataFile fileToRemove = file.FirstOrDefault();
fileToRemove.Drop();
database.Alter();
return "File Removed Successfully";
}
}
}
You can use SetState change the SmoObject status
e.g.
var removeColumn = target.Columns.OfType<Column>().Where(x => !source.Columns.Contains(x.Name)).ToList();
foreach (Column columItem in removeColumn)
{
//If you want remove this item just replace Remove to SetState
columItem.SetState(SqlSmoState.ToBeDropped);
//If I use Remove will got You cannot perform operation Remove on an object in state Existing
//target.Columns.Remove(columItem.Name);
}
I am trying to import bulk data from my csv file. Data gets imported correctly but it adds under double quote (""). I don't want it to add it. Below is code I am using
protected void importSalesData()
{
//Upload and save the file
string csvPath = Server.MapPath("/csv/") + Path.GetFileName(file1.PostedFile.FileName);
file1.SaveAs(csvPath);
string strFile = file1.PostedFile.FileName;
string connectMySQL = ConfigurationManager.ConnectionStrings("loyalty").ConnectionString;
using (MySqlConnection cn1 = new MySqlConnection(connectMySQL)) {
cn1.Open();
MySqlBulkLoader bcp1 = new MySqlBulkLoader(cn1);
bcp1.TableName = "salesData";
//Create ProductOrder table into MYSQL database...
bcp1.FieldTerminator = ",";
bcp1.LineTerminator = Constants.vbCr + Constants.vbLf;
bcp1.FileName = "F:/MY WEB/Foxbox Loyalty/Foxbox Loyalty/website/csv/" + strFile;
bcp1.NumberOfLinesToSkip = 1;
bcp1.Load();
}
}
Try setting the MySqlBulkLoader.FieldQuotationCharacter property to " (double quote) and MySqlBulkLoader.FieldQuotationOptional to false.
MySqlBulkLoader constructs a MySQL LOAD DATA command and then executes it. The documentation does not clearly describe what affect these properties has on loading the data, however, the source code does.
in my case i wanted to display items from local SQLite database which i created as shown below:
public string CreateDB() //create database
{
var output = "";
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "IsoModule.db3");
output = "Database Created";
return output;
}
public string CreateTable() //create table
{
try
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "IsoModule.db3");
var db = new SQLiteConnection(dbPath);
db.CreateTable<UserInfo>();
db.CreateTable<TableInfo>();
string result = "Table(s) created";
return result;
}
catch (Exception ex)
{
return ("Error" + ex.Message);
}
}
and this is my code where i wish to retrieve data
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "IsoModule.db3");
var tablelistout = new SQLiteConnection(path);
var alltables = tablelistout.Table<TableInfo>();
foreach (var listing in alltables)
{
var from = new string[]
{
listing.tname + " - " + listing.status
};
ListView listtable = (ListView)FindViewById(Resource.Id.listtable);
listtable.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, from);
}
the code runs with NO ERROR but it only display last item in the table. it is confusing me, so i would like to ask how can i retrieve all the data from specific table?
or if someone has asked the same question please share me the link. many appreciate.
var alltables = tablelistout.Table<TableInfo>();
var data = new List<string>();
foreach (var listing in alltables)
{
data.Add(listing.tname + " - " + listing.status);
}
ListView listtable = (ListView)FindViewById(Resource.Id.listtable);
listtable.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, data.ToArray());
All I did was move 2 things out of the loop. First, I moved out the initialization of the array. Second, I moved out the listView + assignation of the adapter.
Your issue is that in the loop, you were always overriding everything you had done in the previous iteration (leaving you with the last item like you said).
Also, You should take note that it will be important for you to create a custom adapter if you plan on having a decent amount of data. ArrayAdapter is a native Android class which is then wrapped by a C# Xamarin object, meaning you will have both a C# and Java object per row. It adds overhead as both garbage collectors will have work to do and can cause performance issues. Xamarin devs tend to generally avoid it with the exception of quick prototyping.
On another note, I would use the FindViewById<T>(Int32) instead of the FindViewById(Int32) and casting it. FindViewById<ListView>(Resource.Id.listtable) in your case. Just taking advantage of the power of generics.
I am woking on Microsoft Sync Framework with sql server 2008 and c# below is my code
public static void SetUp(string _pScopeName, DbSyncTableDescription _pDbSyncTable, SqlConnection serverConn, SqlConnection clientConn)
{
// Create a scope named "_ITEM" and add tables to it.
DbSyncScopeDescription productScope = new DbSyncScopeDescription(_pScopeName);
// Define the Products table.
// Add the Table to the scope object.
productScope.Tables.Add(_pDbSyncTable);
// Create a provisioning object for "_ITEM" and apply it to the on-premise database if one does not exist.
SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, productScope);
serverProvision.ObjectSchema = ".dbo";
string _tblName = _pDbSyncTable.LocalName.Replace("[", "").Replace("]", "");
serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip);
serverProvision.Tables[_tblName].AddFilterColumn("_WORKGROUPNAME");
serverProvision.Tables[_pDbSyncTable.LocalName].FilterClause = "[" + _tblName + "].[_WORKGROUPNAME] = " + _CCompanyVar._WORKGROUPNAME;
//Skip create Sync Framework objects because we have already created them on the previous step
serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip);
//Create new select changes procedure for our scope
serverProvision.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create);
if (_CPubVar._Stop_bool)
{
return;
}
if (!serverProvision.ScopeExists(_pScopeName))
serverProvision.Apply();
// Provision the SQL client database from the on-premise SQL Server database if one does not exist.
SqlSyncScopeProvisioning clientProvision = new SqlSyncScopeProvisioning(clientConn, productScope);
if (_CPubVar._Stop_bool)
{
return;
}
if (!clientProvision.ScopeExists(_pScopeName))
clientProvision.Apply();
}
i am getting Error :
The multi-part identifier "_ATTENDANCESTATUS._WORKGROUPNAME" could not be bound.
Invalid column name 'FPR'.
at line :
serverProvision.Apply();
if i remove below lines my Sync process work correctly without filter
string _tblName = _pDbSyncTable.LocalName.Replace("[", "").Replace("]", "");
serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip);
serverProvision.Tables[_tblName].AddFilterColumn("_WORKGROUPNAME");
serverProvision.Tables[_pDbSyncTable.LocalName].FilterClause = "[" + _tblName + "].[_WORKGROUPNAME] = " + _CCompanyVar._WORKGROUPNAME;
//Skip create Sync Framework objects because we have already created them on the previous step
serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip);
//Create new select changes procedure for our scope
serverProvision.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create);
_WORKGROUPNAME is a common field in my all tables and I want to filter data on _WORKGROUPNAME which i pass value in _CCompanyVar._WORKGROUPNAME (string variable)...
where I am wrong please point out ...
use this ...
public static void SetUp(string _pScopeName, DbSyncTableDescription _pDbSyncTable, SqlConnection serverConn, SqlConnection clientConn)
{
// Create a scope named "_ITEM" and add tables to it.
DbSyncScopeDescription productScope = new DbSyncScopeDescription(_pScopeName);
// Define the Products table.
// Add the Table to the scope object.
Collection<string> includeColumns = new Collection<string>();
for (int i = 0; i < _pDbSyncTable.Columns.Count; i++)
{
includeColumns.Add(_pDbSyncTable.Columns[i].UnquotedName);
}
DbSyncTableDescription productDescription = SqlSyncDescriptionBuilder.GetDescriptionForTable(_pScopeName, includeColumns, serverConn);
productScope.Tables.Add(productDescription);
// Create a provisioning object for "_ITEM" and apply it to the on-premise database if one does not exist.
SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, productScope);
serverProvision.ObjectSchema = ".dbo";
// Filter Rows for the ListPrice column
serverProvision.Tables[ _pDbSyncTable.LocalName].AddFilterColumn("_WORKGROUPNAME");
serverProvision.Tables[ _pDbSyncTable.LocalName].FilterClause = "[side].[_WORKGROUPNAME] = '" + _CCompanyVar._WORKGROUPNAME + "'";
if (_CPubVar._Stop_bool)
{
return;
}
if (!serverProvision.ScopeExists(_pScopeName))
serverProvision.Apply();
// Provision the SQL client database from the on-premise SQL Server database if one does not exist.
SqlSyncScopeProvisioning clientProvision = new SqlSyncScopeProvisioning(clientConn, productScope);
if (_CPubVar._Stop_bool)
{
return;
}
if (!clientProvision.ScopeExists(_pScopeName))
clientProvision.Apply();
}
I am using SQLite database for my Windows Store app. I completed my requirement of usage of Database with the help of MSFT samples & Blogs. Now I want to Change/Update the Data which is in the Database File..
My Insert code like this..
using (var db = new SQLite.SQLiteConnection(dbpath))
{
db.Insert(new ItemEpub.EpubBookList()
{
BookName = file.DisplayName,
BookPath = file.Path,
}
);
db.Commit();
db.Dispose();
db.Close();
}
I didn't get the Syntax & any simple information about Update the Database table.
Right now my code is:
StorageFile DataFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Epub.db3");
using (var db = new SQLite.SQLiteConnection(dbpath))
{
db.Update EpubBookList Set
string sql = UPDATE EpubBookList SET LastVisitedPage = '" + lastVisistedPageIndex + "',";
db.Dispose();
db.Close();
}
May be this code looks like ugly, Apart from this code give me any Suggestion on Update the Exiting row in metro apps
To update the existing record, first you need to get that object via SQL query [Query<T>(...)] or Get<T>(...) method. Then update the object properties and call Update(...) method.
using (var db = new SQLite.SQLiteConnection(dbpath))
{
var objPerson = db.Query<Person>("select * from dbPerson where PersonId = ?", 9);
/*** or ***/
var objPerson = db.Get<Person>(9); // Here 9 is primary key value
/*** update the object ***/
objPerson.FirstName = "Matt";
db.Update(objPerson);
}
You don't need to call db.Dispose(); & db.Close(); because you are using using.