Connect Node with mysqli module? - mysql

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.

Related

using mysql in Electron

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)

Node.Js - no output from mysql connection

Sorry in advance - using nodejs for the first time..
I have installed nodejs and npm manager on linux machine. Through the npm I installed mysql module and now I try to test the mysql connection using the simple code. The problem is - no output is printed to the console, when the mysql related code is run!
source:
var mysql = require("mysql");
console.log('1');
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "xxx",
password: "xxxx",
database: "xxx",
port: 3306
});
console.log('2');
connection.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
console.log('3');
connection.end(function(err) {
console.log('Connection closed');
});
console.log('4');
process.exit();
The output is 1234:
Here are installed modules:
So my question is - why are there no messages coming from mysql connection? I tried to enter incorrect connection details on purpose - no messages were produced.
I also tried running node as sudo and also tried running nodejs index.js instead of node index.js. Oh, and I also tried to install and use nodejs-mysql module instead of mysql. Nothing seems to be working.
You're writing asynchronous code, so you need to wait for those operations to complete before you force kill the process.
What you're essentially saying is "Do this, do this, do this, and get back to me later. Also shut everything down right now."
Remove the process.exit call or move it inside a callback function so it's triggered at the right time:
var connection = mysql.createConnection({
...
});
console.log('2');
connection.connect(function(err){
if(err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
console.log('3');
connection.end(function(err) {
console.log('Connection closed');
console.log('4');
process.exit();
});
});
This aggressive nesting and re-nesting is why things like promises exist. Bluebird is a great library for implementing and using these and is used by database wrappers like Sequelize to keep your code organized.

How to create MySQL database connection in Coffeescript

How to connect MySQL database in CoffeeScript. How to run this.I created MySQL connection using node.js and display record in terminal but how to display this on browser.I am using ECO templating for displaying on browser. I need database connection using coffeescript
file - db_test.js
var mysql = require("mysql");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test"
});
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
con.query('SELECT * FROM users',function(err,rows){
if(err) throw err;
for (var i = 0; i < rows.length; i++) {
console.log(rows[i].username);
};
});
con.end(function(err) {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
CoffeeScript is just javascriptâ„¢
Any javascript library should be usable in CoffeeScript because at the end of the day, the CS is just getting converted to JS and running in your usual runtime. This means you would connect just the same (same libraries, methods, etc), just different syntax.
The only advantage of CoffeeScript is that it's nicer to write than JS, if you don't know CoffeeScript, there's little reason to use it at all, and in fact you're just making your life harder by adding a compilation step to your production.
If you must absolutely use CS, there are tools to cross-compile between the two (like js2.coffee), but I strongly suggest you learn CoffeeScript and write it on your own so you get its advantages and not just its burdens. There are plenty of resources online.

How to use existing wamp's MySQL databases in node.js?

I already have WAMP server installed on my machine. Can I be able to access MySQL databases created on WAMP's MySQL using node-mysql module?
Actually, I tried this code, its running without errors but unable to fetch the database(or tables):
var http = require('http'),
mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "database_name"
});
http.createServer(function (request, response) {
request.on('end', function () {
connection.query('SELECT * FROM table_name', function (error, rows, fields) {
console.log('The first field is: ', rows[0].field);
});
});
}).listen(8001);
console.log("running on localhost:8001");
Try adding request.resume(); before your 'end' event handler.
In node v0.10+, streams start out in a "paused" state that allow you to .read() specific sized chunks or you can use them like the old streams by attaching a 'data' event handler which causes the stream to be continuously read from.
Calling request.resume(); will also switch to the old stream mode, effectively discarding the request data (because there are no 'data' event handlers) so that your 'end' event handler will be called.

How to connect mysql Database with Dart?

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