I have SQLite dababase in my assets folder.
How to connect the existing SQLite database to Flutter and get all items from the table?
To connect in existing database is :
var dbDir = await getDatabasesPath();
var dbPath = join(dbDir, "app.db");
final myDB = await rootBundle.load('assets/myDb.SQLITE');
List<int> bytes = myDB.buffer.asUint8List(myDB.offsetInBytes, myDB.lengthInBytes);
await File(dbPath).writeAsBytes(bytes);
var db = await openDatabase(dbPath);
can you read here :
https://stackoverflow.com/a/53128435/10649115
And for a complete example you can see this gist:
https://gist.github.com/sergiotucano/57be4db96bfa5d23d68d242d392a9f7d
Related
ive created M0 Cluster Sandbox via Mongo Atlas. It is working pretty nice. But I want to use transactions with it. And I've read that to use transactions I need to have a replica set.
In the Atlas it seems like my DB have a replicaSet already (i didn't do anything). So how i can connect to that replica set?
My current connection link is mongodb+srv://admin:password#de.xxx.mongodb.net/db?retryWrites=true&w=majority
Thanks in advance!
It should be enough with passing the connection string when you create your MongoClient object:
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "your_string_connection";
const client = new MongoClient(uri, { options-you-need });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
This code was copy-pasted from atlas cluster instructions to connect to the cluster: Connect your applications -> check Include full driver code example.
I have created windows flutter windows application now trying to save local data. I used shared_preferences plugin but it does not support windows applications so I found another package to save local data, sqflite_common_ffi plugin.
But don't know how to use it. I followed it's example and it worked but now want to separate it's all functionalities like I want to create a database in a method , and insert values in another method, get values in another method and delete them in another method.
CODE
import 'package:sqflite_common/sqlite_api.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
class Storages{
var databaseFactory = databaseFactoryFfi;
Database db;
createDatabase ()async{
// Init ffi loader if needed.
sqfliteFfiInit();
db = await databaseFactory.openDatabase(inMemoryDatabasePath);
await db.execute('''
CREATE TABLE Credential(
id INTEGER PRIMARY KEY,
token TEXT,
password TEXT
)
''');
}
saveToken(String token)async{
await db.insert('Credential', <String, dynamic>{'token': token});
}
savePassword(String password)async{
await db.insert('Credential', <String, dynamic>{'password': password});
}
getToken()async{
var result = await db.query('Credential');
print('Credential token database;$result');
// await db.close();
}
getPassword()async{
var result = await db.query('Credential');
print('Credential password database;$result');
}
}
then first I initialized database saved the password in database from login screen but when I restart my application
and I called getpassword method from initState of my splash screen.
Storages storage = new Storages();
#override
void initState() {
super.initState();
storage.getPassword();
}
and thrown me this exception in my terminal
Unhandled Exception: NoSuchMethodError: The method 'query' was called on null.
Receiver: null
Tried calling: query("Credential")
Requirement - I am trying to connect to azure SQL DB from a asp.net MVC application and the connection type to azure SQL DB is "token based" and below are the set up done from my end.
a. Created an AAD application( ex : MTSLocal ) with certificate based authentication.
b. Added permission to the above AAD in SQL.
CREATE USER [MTSLocal] FROM external provider;
c.In code level I am trying to get a access token by using Client ID( obtained from step a.) and certificate and the resource I am connecting to is "https://database.windows.net". Please refer the sample code -
string authority = string.Format(System.Globalization.CultureInfo.InvariantCulture, "https://login.windows.net/{0}",
"xxxx.onmicrosoft.com");
var authContext = new AuthenticationContext(authority);
AuthenticationResult result = null;
result = await authContext.AcquireTokenAsync("https://database.windows.net", AssertionCert);
token = result.AccessToken;
d. I am able to retrieve the access token but when I am trying to open the SQL connection.I am getting the above said error.
sqlBuilder["Data Source"] = serverName;
sqlBuilder["Initial Catalog"] = databaseName;
sqlBuilder["Connect Timeout"] = 30;
string accesstoken = GetAccessToken();
using (SqlConnection connection = new SqlConnection(sqlBuilder.ConnectionString))
{
try
{
connection.AccessToken = accesstoken;
connection.Open();
}
catch (Exception ex)
{
}
}
Any help on this would be really helpful.
Here is some rough and ready code on how I solved this. I had to supply the host tenant (see in the code below.
private async Task<string> SqlServerVersion()
{
var provider = new AzureServiceTokenProvider();
var token = await provider.GetAccessTokenAsync("https://database.windows.net/", "<host tenant>.onmicrosoft.com").ConfigureAwait(false);
SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder
{
csb.DataSource = "<your server>.database.windows.net";
csb.InitialCatalog = "<your database>";
};
using (var conn = new SqlConnection(csb.ConnectionString))
{
conn.AccessToken = token;
await conn.OpenAsync().ConfigureAwait(false);
using (var sqlCommand = new SqlCommand("SELECT ##VERSION", conn))
{
var result = await sqlCommand.ExecuteScalarAsync().ConfigureAwait(false);
return result.ToString();
}
}
}
The Application Registered in the AAD should be added to the users list of the DB and respective roles should be given to DB USER.
For suppose the name of the App registered is "App_AAD_Register_Name". add this user to the corresponding DB like executing the below query. With this the user will be added to Principal Users list of the DB server.
CREATE USER [App_AAD_Register_Name] FROM EXTERNAL PROVIDER.
Create some generic Role like below
CREATE ROLE [RoleUser]
GO
GRANT SELECT ON SCHEMA :: dbo TO [RoleUser]
GO
GRANT INSERT ON SCHEMA :: dbo TO [RoleUser]
GO
Once Role is created and respective permissions are given, assign the role to the user created in the first step.
EXEC sp_addrolemember N'RoleUser', N'App_AAD_Register_Name'.
Once all these steps are done you will be able to connect to DB with the token.
These steps worked for me.
I am trying to export a table from a Cloud SQL database owned by another project. The calling project has access and can successfully list instances (using getItems()), but it when I try to export is returns "The client is not authorized to make this request."
Here is the code that I am using to export.
$client = new Google_Client();
$client->setAuth(new Google_Auth_AppIdentity($client));
$client->getAuth()>authenticateForScope('https://www.googleapis.com/auth/sqlservice.admin');
$client->getAuth()>authenticateForScope('https://www.googleapis.com/auth/cloud-platform');
$sqladmin = new Google_Service_SQLAdmin($client);
$postBody = new Google_Service_SQLAdmin_InstancesExportRequest();
//Set csv options
$csv_options = new Google_Service_SQLAdmin_ExportContextCsvExportOptions();
$csv_options->setSelectQuery('SELECT id FROM test.test;');
//set export context options.
$ec = new Google_Service_SQLAdmin_ExportContext();
$ec->setCsvExportOptions($csv_options);
$ec->setUri('gs://bucket/file.csv');
$postBody->setExportContext($ec);
$response = $sqladmin->instances->export('testing-project-xxxx', 'database', $postBody);
$response = $sqladmin->instances->export('testing-project-xxxx', 'database', $postBody);
Replace database name with instance name
I am working on a Grails appplication, In this I have to copy all production server database to local database first. I am having DataSource.groovy as follows :
dataSource {
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
dialect = org.hibernate.dialect.MySQLDialect
username = "xxxx"
password = "xxxx"
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}
// environment specific settings
environments {
development {
dataSource {
url = "jdbc:mysql://xxxx"
username = "xxxx"
password = "xxxx"
}
}
test {
dataSource {
//dbCreate = "update"
url = "jdbc:mysql://xxxx"
}
}
production {
dataSource {
url = "jdbc:mysql://xxxx_production"
username = "xxxx"
password = "xxxx%"
}
}
staging {
dataSource {
url = "jdbc:mysql://xxxx"_staging"
username = "xxxx"
password = "xxxx%"
}
}
}
Is there any command in Grails for copy production environment database to local or staging environment database.
Thanks.
Use tools for your current production database to create and apply dumps. Database management is not a grails job.
We create sql dumps or backups of the production database, and then you just restore it locally.
You can use Grails Database Migration Plugin.
For further details refer http://grails-plugins.github.io/grails-database-migration/docs/manual/guide/gettingStarted.html