I am using sqlite3 with fmdb and xcode6.1 (swift).
In my application, need to update some data from db.
It’s updated.
But when I have checked in sqliteBrowser ,it didn’t update.(that sqlite file is in my project folder).
Is it normal ??
or Something wrong??
I am confused because when I restart my app, it's really updated.(not updated only when I have checked db with sqliteBrowser)
var database:FMDatabase!
let resourcePath = NSBundle.mainBundle().resourceURL!.absoluteString
let dbPath = resourcePath?.stringByAppendingPathComponent("mydbname.sqlite")
let dbTest = FMDatabase(path: dbPath)
if (!dbTest.open()) {
println("Could not open database at \(dbPath).")
} else {
println("open database at \(dbPath).")
var sql = "UPDATE tblEducation SET edu_fav = 0"
let results = dbTest.executeUpdate(sql, withArgumentsInArray: nil)
if results {
println("Success Update")
}
When you run sql file from your project and make changes with it. For that App create a sqlite file to your project folder and do changes with it only. So if you want to see changes done in simulator than check into project directory and database file.
Related
I am trying to connect SQLite DB file to my unity project where db file is present in downloads folder but I am unable to get data from tables. How can I connect download folder contain DB file to unity project SQLite. My requirement is able to run a project with downloaded db file which is present in the downloads folder. Please suggest any idea. Thanks in advance. Here is the code I am using for connecting db file to SQLite.
Sample code :
Debug.Log("Call to OpenDB:" + databaseName);
var tempdbPath = Path.GetFullPath("log -29-10-2018 - .db");
var tempdbbytes = File.ReadAllBytes(tempdbPath);
var _filePath = tempdbPath;
ApplicationContext.CurrentDatabasePath = _filePath;
//open db connection
_connectionString = "URI=file:" + _filePath;
(where _filePaht = /Users/deepak/Projects/testproject/test/log -29-10-2018 - .db)
ApplicationContext.TempConnectionString = _filePath;
ApplicationContext.ConnectionString = _connectionString;
Debug.Log("Stablishing connection to: " + _connectionString);
dbcon = new SqliteConnection(_connectionString);
dbcon.Open();
}
catch (Exception exception)
{
LoggingManager.Error(exception);
}
}
When I connect persistence folder contain db file it's working well, I am getting a problem when I am trying to connect db file present in the downloads folder.
I'm trying to build APIs using Swift and I've chosen to use Vapor.
I've created a SQLite database and am able to connect to it using a DB client.
Now I want my Swift Vapor project to connect to it as well using the FluentSQLite package.
I've created my database in the root folder of my project:
/Users/rutgerhuijsmans/Documents/runk-3.0
My database is called runk-3.0-database
The folder looks like this:
I try to connect to my DB using the following configuration:
import FluentSQLite
import Vapor
/// Called before your application initializes.
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
/// Register providers first
try services.register(FluentSQLiteProvider())
/// Register routes to the router
let router = EngineRouter.default()
try routes(router)
services.register(router, as: Router.self)
/// Register middleware
var middlewares = MiddlewareConfig() // Create _empty_ middleware config
/// middlewares.use(FileMiddleware.self) // Serves files from `Public/` directory
middlewares.use(ErrorMiddleware.self) // Catches errors and converts to HTTP response
services.register(middlewares)
let sqlite: SQLiteDatabase?
do {
sqlite = try SQLiteDatabase(storage: .file(path: "runk-3.0-database"))
print("data base connected") // This gets printed
/// Register the configured SQLite database to the database config.
var databases = DatabasesConfig()
databases.add(database: sqlite!, as: .sqlite)
services.register(databases)
/// Configure migrations
var migrations = MigrationConfig()
migrations.add(model: User.self, database: .sqlite)
services.register(migrations)
} catch {
print("couldn't connect") // This doesn't get printed
}
}
What am I doing wrong?
As IMike17 explained, your code just creates the new DB file into the Build/Products/Debug or release folder. You have to set full path dynamically as below:
do {
let directory = DirectoryConfig.detect()
let filePath = directory.workDir + "runk-3.0-database"
sqlite = try SQLiteDatabase(storage: .file(path: filePath))
......
Using the .file(path: "runk-3.0-database") the method, if you specify only the name, creates a database file with the specified name in the Derived Data folder. If the file exists in the Derived Data folder, SQLiteDatabase uses it. So the DB is erased when cleaning the build folder.
The console prints out the path of the Derived Data where you can find the DB:
Running default command: /Users/username/Library/Developer/Xcode/DerivedData/SQLiteDB-xxxxxxxxxxxxxxxxxxxxxxx/Build/Products/Debug/
If you use a full path to the DB in your project then the file is used.
Change your init method as follows and you should be good to go for a local environment:
sqlite = try SQLiteDatabase(storage: .file(path: "/Users/rutgerhuijsmans/Documents/runk-3.0/runk-3.0-database"))
I'm building an app and I need a connection with a database. I'm using Parse for this (and hosting it with back4app if that does matter).
I have already a lot of experience with Parse so it's very weird that I have this problem.
So I need to update an object but it doesn't. Could somebody please help me out? I've putted in my code an print and it does print so you know the app get's there but strangely enough, it doesn't update the object.
Thanks in advance!
EDIT: the code works because when I run the app in the simulator it updates but when I run it on my iPhone, it doens't?
func makeMessagesSeen() {
let query = PFQuery(className: "Chat")
query.whereKey("senderID", equalTo: otherID)
query.whereKey("receiverID", equalTo: yourID)
query.order(byDescending: "createdAt")
var objects = try! query.findObjects()
for i in objects {
if (objects[0].objectId == i.objectId) {
print("this will print , idk why code beneath this doesn't work?")
i["messageSeen"] = "last seen"
i.saveInBackground()
}
else {
i["messageSeen"] = "seen"
i.saveInBackground()
}
}
}
I fixed it and will post the solution here in case anyone will make the same mistake.
So I created the message object with my simulator and parse automatically set the write acces for everyone to false. Only for the device that created the message it was set to true. So that's why I could only update to object with my simulator.
So change in your database the write acces for everyone to true.
Using code to Preserve access to a StorageFolder stolen from Karl Erickson
public static async Task<StorageFolder> GetOrPickAndRememberFolderAsync(string key)
{
if (StorageApplicationPermissions.FutureAccessList.ContainsItem(key))
{
return await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(key);
}
var picker = new FolderPicker();
picker.FileTypeFilter.Add("*");
StorageFolder folder = await picker.PickSingleFolderAsync();
if (folder != null)
{
StorageApplicationPermissions.FutureAccessList.AddOrReplace(key, folder);
}
return folder;
}
our UWP app is able to browse to and remember the location of a SQLite database chosen by a user. This should give read/write permissions on that folder.
The dbContext is instantiated like this
public dbContext(string dbPath)
{
databasePath = dbPath;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=" + databasePath);
}
This code works if the user chooses the default local storage location for the app.
var picker = new FolderPicker();
picker.FileTypeFilter.Add("*");
StorageFolder folder = await picker.PickSingleFolderAsync();
StorageFolder dbFolder = await GetOrPickAndRememberFolderAsync("LocalDbFolder");
string dbPath = Path.Combine(dbFolder.Path, "MySQLite.db");
using (var db = new dbContext(dbPath))
{
db.Database.Migrate();
}
However if the user chooses any other location (such as their Documents folder) the app fails with the error "SQLite Error 14: 'unable to open database file'."
Why would that be, given the user has given the app explicit permissions on the selected location through the picker?
You can't.
SQLite requires native file access. To use the native file access, you should put the sqlite .db file to the application local folders - Windows.Storage.ApplicationData.Current.LocalFolder or tempfolder.
If you use the file/folder picker, you can get the storagefolder item. But, if the folder is outside of your application, ALL of file accesses are done with OS's broker process. SQLite can't access the such of folders.
I am trying to create a image by fetching blob from MySQL DB ...
Here goes the code....
var dbConn = DatabaseConnectionFactory.createDatabaseConnection('com.mysql.jdbc.Driver','jdbc:mysql://localhost:3306/dbname','username','');
var query_code = "Select blob from tblname where id =59"; //
var result = dbConn.executeCachedQuery(query_code);
dbConn.close();
if (result.next())
{
var image=FileUtil.encode(result.getBytes(1));
$gc('image1', image);
}
Could anyone help me out to achieve this...
Did You receive any error with this code if so post it.
Im not sure with Mirth connect tool But as far as I know, Retrieving the BLOB image from the DB directly with any IDE/Tools is always possible but difficult with 2 ways
By encoding to BASE-64 charcter
By specifying the entire location saving it locally.
And try removing the dbconn.close(); do not use it or use it after if() statement. Because it will throw an error like "no statements were executed after dbconn.close();