Does anyone can tell me how to connect to mysql database with Dart? I've been reading and searching for days but can't find any suitable answers. I just learning web programming. Thank you!
You can use SQLJocky to connect to MySQL. Add
dependencies:
sqljocky: 0.0.4
to your pubspec.yaml an run pub install. Now you can connect to MySQL like this
var cnx = new Connection();
cnx.connect(username, password, dbName, port, hostname).then((nothing) {
// Do something with the connection
cnx.query("show tables").then((Results results) {
print("tables");
for (List row in results) {
print(row);
}
});
});
I think for dart 2 mysql1 is a simple choice.
Example:
import 'package:mysql1/mysql1.dart';
Future main() async {
// Open a connection (testdb should already exist)
final connection = await MySqlConnection.connect(new ConnectionSettings(
host: '10.0.2.2',
port: 3306,
user: 'root',
password: '0123456789',
db: 'development',
));
var results = await connection.query('select * from tableName');
for (var row in results) {
print('${row[0]}');
}
// Finally, close the connection
await connection.close();
}
(tested on Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297))
I haven't tried this, but here is one: http://github.com/jamesots/sqljocky
You can try using sqljocky -> http://pub.dartlang.org/packages/sqljocky
Related
I have a Node.js Stackblitz project that I am trying to connect to a remote MySQL database. It is not possible to have a MySQL database within Stackblitz, hence trying the remote approach. However I get "Error: connect ETIMEDOUT" whenever I attempt a connection. Any help or pointers much appreciated.
I am using the code below. The remote database is accessible with the credentials I am using and returning data when used outside of Stackblitz. Is remote database access not possible with Stackblitz or am I missing something?
const express = require('express');
const mysql = require('mysql2/promise');
const app = express();
const port = 3010;
const path = require('path');
app.use(express.static('static'));
app.get('/', async function (req, res) {
try {
// create connection
const connection = await mysql.createConnection({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_DATABASE,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
});
// query database
const [rows, fields] = await connection.execute('SELECT * FROM `user`');
res.send({
rows,
fields,
});
} catch (err) {
console.log('err:', err);
}
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
For anyone looking for an explanation.
Currently a mysql database cannot reside in StackBlitz. Additionally, neither can it connect to an external mysql database on its own either.
You therefore required a backend API outside of StackBlitz to make the database calls, negating the reason for building the backend on StackBlitz in the first place (IMO). Therefore, the suggested setup currently would be a localhost backend API accessed from a frontend in StackBlitz via an ngrok secure address.
StackBlitz are working on getting basic server requests running in the future. So, watch this space.
I hope this answer helps save others time.
Trying to build a backend database for my React app, and upon trying to import the relevant MySQL libraries, it throws an error. There are no problems when I run it from the terminal, but the moment I put it in, I receive the following error:
./src/data/node_modules/mysql/node_modules/safe-buffer/index.js
Line 1:1: Definition for rule 'node/no-deprecated-api' was not found node/no-deprecated-api
Have not been able to find any solutions while searching.
My code:
import {mysql} from 'mysql'; // Commenting out this one line stops the error
export default function tester() {
/*
const connection = mysql.createConnection({ // Commented out only when import is commented
host: 'localhost',
user: '<username>',
password: '<password>',
database: '<db name>'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
*/
}
To anyone reading this in the future, the solution was to not connect directly to the MySQL server, instead to use Express.
I'm building an Node application which will query simple and more complex (multiple joins) queries. I'm looking for suggestions on how I should manage the mySQL connections.
I have the following elements:
server.js : Express
router1.js (fictive name) : Express Router middleware
router2.js (fictive name) : Express Router middleware
//this is router1
router.get('/', function (req, res){
connection.connect(function(Err){...});
connection.query('SELECT* FROM table WHERE id = "blah"', function(err,results,fields){
console.log(results);
});
...
connection.end();
})
Should I connect to mysql everytime '/router1/' is requested, like in this example, or it's better to leave one connection open one at start up? As: connection.connect(); outside of: router.get('/',function(req,res){
...
}); ?
I am using mysql2 for this, it is basicly mysql but with promises. If you use mysql you can also do this.
Create a seperate file called connection.js or something.
const mysql = require('mysql2');
const connection = mysql.createPool({
host: "localhost",
user: "",
password: "",
database: ""
// here you can set connection limits and so on
});
module.exports = connection;
Then it is probaly better you create some models and call these from within your controllers, within your router.get('/', (req, res) => {here});
A model would look like this:
const connection = require('../util/connection');
async function getAll() {
const sql = "SELECT * FROM tableName";
const [rows] = await connection.promise().query(sql);
return rows;
}
exports.getAll = getAll;
You can do this with or without promises, it doesn't matter.
Your connection to the pool is automatically released when the query is finished.
Then you should call getAll from your router or app.
I hope this helped, sorry if not.
Connection pooling is how it should be done. Opening a new connection for every request slows down the application and it can sooner or later become a bottleneck, as node does not automatically closes the connections unlike PHP. Thus connection pool ensures that a fixed number of connections are always available and it handles the closing of unnecessary connections as and when required.
This is how I start my express app using Sequelize. For Mongoose, it is more or less simlar except the library API.
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
sequelize.authenticate()
.then(
// On successfull connection, open a port
// and listen to requests. This is where the application
// starts listening to requests.
() => {
const server = http.createServer(app);
server.listen(port);
},
)
.catch(err => {
console.error('Unable to connect to the database:', err);
console.error('Cancelling app server launch');
});
The app is started only after a database connection has been established. This ensures that the server won't be active without any database connection. Connection pool will keep the connections open by default, and use a connection out of the pool for all queries.
If you use createPool mysql will manage opening and closing connections and you will have better performance. It doesn't matter if you use mysql or mysql2 or sequlize. use a separate file for createPool and export it. You can use it everywhere. Don't use classes and just do it functionally for better performance in nodejs.
> npm install mysql
mysql is a great module which makes working with MySQL very easy and it provides all the capabilities you might need.
Once you have mysql installed, all you have to do to connect to your database is
var mysql = require('mysql')
var conn = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database'
})
conn.connect(function(err) {
if (err) throw err
console.log('connected')
})
Now you are ready to begin writing and reading from your database.
I want to connect Node JavaScript with Mysqli. I have downloaded the mysqli module using following command.
npm install mysqli
And Then Create JavaScript file with following code.
var Mysqli = require('mysqli');
// incoming json
let conn = new Mysqli ( {
host: "localhost",
user: "root",
password: "",
database: "ll"
} );
conn.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM post", function (err, result) {
if (err) throw err;
console.log(result);
});
});
But not able to connect to database.
I have used following Packages.
https://www.npmjs.com/package/mysqli
You have a typo here:
conn.query
Unless, of course, you wrote the code here again. I am sure you would have figured that out by now, but still... After all, this is the first thing that comes up when someone searches for mysqli nodejs.
If connecting to mysql db is the goal, then I suggest you to use mysql module.
install mysql module by running npm install mysql
below is the sample code for how to use the mysql module
const mysql = require('mysql');
const conn = mysql.createConnection(
{
host:'your_host', //localhost in your case
user:'db_user', // root in your case
password: 'password', //blank string in your case
database:'your_db_name' //'ll' in your case
});
//executing the queries
conn.query('SELECT * from post',function(err,result){ //result of the query is stored in 'result' and the error, if any, are stored in err
if(err)
{
console.log(err);
}
else
{
console.log(result);
}
});
click this link for further information
The module which you're using seems to be a newer one and which is not stable.
Consider using mysql module which has been accepted by many developers, it has a great documentation and an active github community + google mailing list and IRC channel.
Im trying to use mysql in electron but i'm running into this error
TypeError: Invalid data, chunk must be a string or buffer, not object
at Socket.write (net.js:667)
at Protocol.<anonymous> (Connection.js:100)
with this code
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'host address',
user: 'username',
password: 'pw',
database: 'db name',
});
con.connect(err => {
if(err) throw err
})
con.query('select * from BOOKS', (err2, result) => {
if(err2) {
throw err2;
}
console.log(result);
})
if i paste this into a test.js file and run it with node then it runs 100% fine without errors, so im not really sure where im going wrong here
So it turns it my issue had something to do with the fact that I was running Angular on electron. if I put that code inside my Angular code it would error out but if I put it in the index.html it would run fine.
So I just made a little proxy function in the index.html for connecting to the DB and making queries, then i'd jsut call it from inside the Angular app without a problem like window.mysqlQuery(queryString)