I just built flutter environment on Mac yesterday and started to learn.
trying to get data from mysql following the tutorial
https://www.youtube.com/watch?v=ig6WRq73iEg&t=165s&ab_channel=JesusHedo
here is my code
mysql.dart file
import 'package:mysql1/mysql1.dart';
class Mysql {
static String host = '127.0.0.1',
user = 'root',
password = 'justin',
db = 'users_test_MAC';
static int port = 3306;
Mysql();
Future<MySqlConnection> getConnection() async {
var settings = new ConnectionSettings(
host: host, port: port, user: user, password: password, db: db);
return await MySqlConnection.connect(settings);
}
}
related function in main.dart
void _getname() {
db.getConnection().then((conn) {
// String sql = 'insert into `userstable` values(50,"justin3","jsutin#gmail",26);';
// this describe can work
String sql = 'select `name` from `userstable` where id = 20;';
conn.query(sql).then((results) {
for (var row in results) {
setState(() {
name = row[0];
});
}
});
});
}
however it didn't work.
in debug mode, it showed var is empty while the describe worked when I queried in mysql workbench
BTW, I've tried to insert data and it can work
If anyone knows there got something wrong
You shouldn't work like that.. you need a backend service and work with http client
Related
I am changing the project from expressjs to nestjs.
In express, I added an admin user to the database by default in app.ts.
like this:
public async addDefaultAdmin() {
UserModel.find({ role: Roles.admin }).then(async (superAdmin) => {
if (superAdmin.length === 0) {
try {
const newUser = new UserModel({...});
await this.hashPassWord(newUser);
await newUser.save();
console.log("default admin successfully added.");
} catch (error: any) {
console.log(error);
}
}
});
}
I wanted to know how I can do this in NestJS?
Does NestJS or typeOrm have a solution for this issue?
You may need to use lifecycle events. NestJS fires events during application bootstrapping and shutdown.
According to doc, onApplicationBootstrap() event may be helpful in your case.
Called once all modules have been initialized, but before listening for connections.
However, NestJS does not expose a hook after the application starts listening, so in this case you need to run your custom function inside of bootstrap function right after the server could listen to a port.
The pseudocode would be like this:
// main.ts
import { User } from '/path/to/user.entity';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
...
await app.listen(3000);
let user = app.get(getRepositoryToken(User)); // You need to pass the entity file to typeorm
await addDefaultAdmin(user); // Pass the user model, and call the function
}
bootstrap();
I am able to programmatically log in to the PowerBI Client, gather my Workspaces as well as get a specific Report from a specific Workspace. I need to programmatically render that report to a .pdf or .xlsx file. Allegedly this is possible with the ExportToFileInGroup/ExportToFileInGroupAsync methods. I even created a very simple report without any parameters. I can embed this using the sample app from here. So that at least tells me that I have what I need setup in the backend. But it fails when I try to run the ExportToFileInGroupAsync method (errors below code.)
My Code is:
var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(new string[] {
PowerBiScopes.ReadReport,
PowerBiScopes.ReadDataset,
});
var userInfo = await graphServiceClient.Me.Request().GetAsync();
var userName = userInfo.Mail;
AuthDetails authDetails = new AuthDetails {
UserName = userName,
AccessToken = accessToken,
};
var credentials = new TokenCredentials($"{accessToken}", "Bearer");
PowerBIClient powerBIClient = new PowerBIClient(credentials);
var groups = await powerBIClient.Groups.GetGroupsAsync();
var theGroup = groups.Value
.Where(x => x.Name == "SWIFT Application Development")
.FirstOrDefault();
var groupReports = await powerBIClient.Reports.GetReportsAsync(theGroup.Id);
var theReport = groupReports.Value
.Where(x => x.Name == "No Param Test")
.FirstOrDefault();
var exportRequest = new ExportReportRequest {
Format = FileFormat.PDF,
};
string result = "";
try {
var response = await powerBIClient.Reports.ExportToFileInGroupAsync(theGroup.Id, theReport.Id, exportRequest);
result = response.ReportId.ToString();
} catch (Exception e) {
result = e.Message;
}
return result;
It gets to the line in the try block and then throws the following errors:
An error occurred while sending the request.
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
UPDATE
Relating to #AndreyNikolov question, here is our Embedded capacity:
After this was implemented, no change. Same exact error.
Turns out the issue was on our side, more specifically, security/firewall settings. Here is the exact quote from our networking guru.
"After some more investigation we determined that our firewall was causing this issue when it was terminating the SSL connection. We were able to add a bypass for the URL and it is now working as expected."
I have a use case that many connections to the database are created dynamically using pg-promise. Sometimes I need to connect again to the same database and user however the password changed.
Is there a way to update an existing connection so I dont get the "WARNING: Creating a duplicate database object for the same connection."?
Editing for better explanation:
Context
I have a non-traditional application that is a node service that handles geospatial data aquisition in the software QGIS, with Postgres + PostGIS.
This application creates temporary users in the PostgreSQL server and manage permissions on the tables and columns based on the type of work the user needs to do.
Code
const dbs = {} //global variable that stores all connections
const getConnection = async (user, password, server, port, dbname) => {
const connString = `postgres://${user}:${password}#${server}:${port}/${dbname}`
if (connString in dbs) {
return dbs[connString] //if connection already exists returns the connection
}
dbs[connString] = db.pgp(connString) //create new connection
await dbs[connString] //tests if connections is correct
.connect()
.then(obj => {
obj.done() // success, release connection;
})
.catch(e => {
errorHandler.critical(e)
})
return dbs[connString]
}
What I want is add another case, that if the connection already exists but the password changed it updates the existing connection password (or destroy it and create a new one).
The issue in your case is that you are using password as part of the connection-string key, which isn't used within the library's unique-connection check, hence the side effect.
For the key, you need to use a unique connection string that does not contain the password. And when the request is made, you need to update the connection details.
Example below makes use of the connection object, not the connection string, because it is simpler that way. But if you want, you can use a connection string too, you would just need to generate a separate connection string, with the password, and update $pool.options.connectionString, not $pool.options.password.
const dbs = {}; // global variable that stores all connections
const getConnection = async (user, password, host, port, database) => {
const key = `${user}#${host}:${port}/${database}`; // unique connection key
const cn = { host, port, database, user, password }; // actual connection
let db; // resulting database object
if (key in dbs) {
db = dbs[key];
db.$pool.options.password = password; // updating the password
} else {
db = pgp(cn); // creating new connection
dbs[key] = db;
await db // test if can connect
.connect()
.then(obj => {
obj.done(); // success, release connection;
})
.catch(e => {
errorHandler.critical(e);
throw e;
})
}
return db;
}
After hours of trying. I haven't make it work.
Here's what I have.
var app = require('express')(),
http = require('http').Server(app),
io = require('socket.io')(http),
r = require('rethinkdb');
http.listen(5000);
console.log('Server started on port 5000');
r.connect({db: 'testRealtime'}).then(function(c) {
r.table('messages').insert(
{ message: "realtime" }
)
r.table('messages').changes().run(c)
.then(function(cursor) {
cursor.each(function(err, item) {
io.emit('messages', item)
})
})
})
As you can see on the above example. I am trying to insert a message realtime and look at it on rethinkdb dashboard. But this doesn't work. I don't know why.
Rethinkdb query r.db('testRealtime').table('messages').changes()
Since i'm using angular2. Here's the Service I created
import * as io from 'socket.io-client'
export class ChatService {
private url = 'http://localhost:5000'
private socket;
getMessages() {
this.socket = io(this.url);
this.socket.on('messages', function(data){
console.log(data.new_val.query_engine)
})
}
}
On my component, I just call the getMessages form service. Nothing to worry about angular code. I think it is more about the connection of socket.io and rethinkdb.
Any help would be appreciated. Thanks.
I'm working on a project using pg-promise. I've tried querying a few different ways with pg-promise but they all seem to cause it to hang after 6 queries.
It seems to me like the connections aren't being closed but I can't find anything in the documentation about closing a connection after a query.
Here's what I have
var cn = {
host: 'localhost',
port: 5432,
database: 'db',
user: 'user',
password: 'password'
};
var db = pgp(cn);
function query(sql, params) {
return db.task(function (t) {
// this = t = task protocol context;
// this.ctx = task config + state context;
return t.query(sql, params);
})
.then(function (events) {
// success;
console.log(events);
})
.catch(function (error) {
// error;
});
}
I also tried using a shared connection, object but the documentation recommended using tasks. Does anyone know what's going on here?
I'm not sure if this will be helpful to anyone in the future. But my problem was not return requests to the browser.
I hit the maximum number of connections and no responses to the browser made it appear to be hanging to me. I didn't realize requests is node/express won't automatically return like they do with php/apache.