I have this code on index.js in which i connect to a postgreSQL database and execute a query but it keeps telling me: column "Jhonny" does not exist.
Here is my code:
const {Client} = require ('pg');
const client = new Client({
host: 'localhost',
user: 'postgres',
database: 'React',
password: '01021997',
port: 5432,
})
client.connect();
client.query('INSERT INTO movies (moviename, review) VALUES ("Jhonny", "no
review");', (err, res)=>{
if(!err){
console.log('insert done');
}else{
console.log(err.message);
}
client.end;
})
the query should be in the following way:
client.query(`INSERT INTO "movies" ("moviename", "review") VALUES ('Jhonny',
'no review');`
the column names and the table name should be between ("") and the values should be between ('').
Related
I'm a newbie developer and I've made a code in Node.js to insert an image as varbinary into an SQL Server DB, now I would like to retrieve this image and see it.
For now I just want to be able to see the image, with or without code, so I can figure out my next steps. Here's the code I've written:
var dbConfig = {
server: "localhost\\MSSQLSERVER",
database: "nodeapp",
user: "test",
password: "1234",
port: 1433,
synchronize: true,
trustServerCertificate: true
};
var con = new sql.ConnectionPool(dbConfig);
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO teste (id,nome,img) SELECT 1,'lizzy', BULKCOLUMN FROM OPENROWSET (BULK 'C:\\Users\\lab101a\\Documents\\Mateus\\lizzy.jpeg', Single_Blob) as varbinary";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
I am currently working on login/register API for my database search engine. I am using express#4.17.1, pg#7.18.2, PostgreSQL 12. The problem is that on one of the machines (Ubuntu bionic 18.0.4 LTS) the query for /register route resolves fine - the user is saved in postgres db, but on Fedora 32 the await function takes forever to resolve.
Here is the code:
db.js:
const pool = new Pool({
host: "localhost",
user: "postgres",
password: "postgres",
port: 5432,
database: "jimjones"
});
module.exports = pool;
register route in jwtAuth.js:
router.post("/register", validInfo, async (req, res) => {
const { email, name, password } = req.body;
try {
const user = await pool.query("SELECT * FROM users WHERE user_email = $1", [
email
]);
//doesnt get past first query
if (user.rows.length > 0) {
return res.status(401).json("User already exist!");
}
const salt = await bcrypt.genSalt(10);
const bcryptPassword = await bcrypt.hash(password, salt);
let newUser = await pool.query(
"INSERT INTO users (user_name, user_email, user_password) VALUES ($1, $2, $3) RETURNING *",
[name, email, bcryptPassword]
);
const jwtToken = jwtGenerator(newUser.rows[0].user_id);
return res.json({ jwtToken });
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
});
The query:
const user = await pool.query("SELECT * FROM users WHERE user_email = $1", [
email
]);
The req.body on Fedora 32 is parsed, so it's not a firewall problem regarding the POST request.
Using Postman, the program fails on this query (but only on Fedora 32). Both databases have the same tables on both machines. Sql select query in psql returns data on both machines.
Any suggestions on how to fix/debug this? Any help will be greatly appreciated.
Upgrading to pg#8.3.0 solved this issue.
The whole discussion:
https://github.com/brianc/node-postgres/issues/2069
I am new to Node.js. I am trying to make connection pools with multiple databases. I have successfully made connection pools (i think) with below mentioned code. I know in order to execute query operations i have to do something at "Connection pool DBX Success", but i can't seem to figure out what to do so that i am able to execute queries on desired pool say crm1.execute or crm2.execute. What can i do here to achieve this. The only way i can think of is to write execute functions for each database separately which i know is wrong and i have to work with 15 databases so it isn't possible to write functions for all 15 databases separately.
const config = require("../config/config");
const oracledb = require("oracledb");
crm1 = config.crm1;
crm2 = config.crm2;
const crm1pool = oracledb.createPool ({
user: crm1.user,
password: crm1.password,
connectString: crm1.connectString,
poolMin: 1,
poolMax: 10,
poolTimeout: 300
}, (error,pool)=>{
if (error){
console.log(error);
}
console.log("Connection Pool DB1 success")
});
const crm2pool = oracledb.createPool ({
user: crm2.user,
password: crm2.password,
connectString: crm2.connectString,
poolMin: 1,
poolMax: 10,
poolTimeout: 300
}, (error,pool)=>{
if (error){
console.log(error);
}
console.log("Connection Pool DB2 success")
});
There is a lot of node-oracledb documentation on pooling and examples. Study those first.
Then you might find that giving each pool a poolAlias will let you easily choose which to use:
await oracledb.createPool({
user: 'hr',
password: myhrpw, // myhrpw contains the hr schema password
connectString: 'localhost/XEPDB1',
poolAlias: 'hrpool'
});
await oracledb.createPool({
user: 'sh',
password: myshpw, // myshpw contains the sh schema password
connectString: 'otherhost/OTHERDB',
poolAlias: 'shpool'
});
const connection = await oracledb.getConnection('hrpool');
const result = await connection.execute(
`SELECT manager_id, department_id, department_name
FROM departments
WHERE manager_id = :id`,
[103], // bind value for :id
);
console.log(result.rows);
Im a newbie to orient db .I have a vertex user which has properties adress,name and another vertex Images with properties imagename,date.Both are connected by and edge postedby.Now I want to write a query to select all images posted by a user with all the properties of both the vertices.How can I write the query to get this.I use orientjs in my project
Try this:
var OrientDB = require('orientjs');
var db = OrientDB({
host: 'localhost',
port: 2424,
});
var db = db.use({
name: '<db name>',
username: '<username>',
password: '<pwd>'
});
db.query('select address, name, out("postedby").imagename as imagename, out("postedby").date as date from User where name = "<insert a name>" unwind imagename,date')
.then(function (response) {
console.log(response);
});
db.close();
Hope it helps
Regards
I can't seem to find how to log into a database in my FeathersJS app.
I would prefer to specify database info and login info in the service, but I just need it to work.
In myApp/config/default.json there is the following line:
"postgres": "postgres://postgress:#localhost:5432/feathers_db",
at:
http://docs.sequelizejs.com/en/latest/docs/getting-started/
It says that a string like the above should be:
"postgres": "postgres://username:user_password#localhost:5432/feathers_db",
But this does not work. It is also not very Feathers-like as now I am locked into one postgress db for all my postgress transactions.
In services/index.js there is the following line:
const sequelize = new Sequelize(app.get('postgres'), {
dialect: 'postgres',
logging: false
});
I could customize the above line to be what Sequelize says to do in their guide and have username and password as an argument, but then why is the template not already laid out like this?
There is also this line:
app.set('sequelize', sequelize);
If I have several postgress databases what do I do? DO I make new Sequelize objects and do something like:
app.set('sequelize_db1', sequelize_db1);
app.set('sequelize_db2', sequelize_db2);
Or do I specify db info, including user info in the service's model?
What does the logging in process for Postgress look like if one is using the generic db language rather than sequelize?
So in a word "yes". Everything I asked in my question was yes.
I can connect to the db like shown in the sequelize documentation. I can also configure the config.json file to have a "postgres" configuration with my user and db name. I could also place the full path in the services/index.js file when creating the new sequelize object. The best way to check that there is a connection is to have the following code after creating the new sequelize object:
new_sequelize_object
.authenticate()
.then(function(err) {
console.log('Connection to the DB has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});
(taken from: http://docs.sequelizejs.com/en/latest/docs/getting-started/)
one can also define several sequelize objects and set them in the app. Then when defining the model in the specific service's index.js file, place the new bound name in the app.get('new_sequelize_object').
Here is the services/index.js file with two databases defined:
'use strict';
const service1 = require('./service1');
const authentication = require('./authentication');
const user = require('./user');
const Sequelize = require('sequelize');
module.exports = function() {
const app = this;
const sequelize = new Sequelize('feathers_db1', 'u1', 'upw', {
host: 'localhost',
port: 5432,
dialect: 'postgres',
logging: false
});
const sequelize2 = new Sequelize('postgres://u1:upw#localhost:5432/feathers_db2', {
dialect: 'postgres',
logging: false
});
app.set('sequelize', sequelize);
app.set('sequelize2', sequelize2);
sequelize
.authenticate()
.then(function(err) {
console.log('Connection to sequelize has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});
sequelize2
.authenticate()
.then(function(err) {
console.log('Connection has been established to sequelize2 successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});
app.configure(authentication);
app.configure(user);
app.configure(service1);
};
And here is the service1/index.js file that uses service sequelize2:
'use strict';
const service = require('feathers-sequelize');
const service1 = require('./service1-model');
const hooks = require('./hooks');
module.exports = function(){
const app = this;
const options = {
//Here is where one sets the name of the differeng sequelize objects
Model: service1(app.get('sequelize2')),
paginate: {
default: 5,
max: 25
}
};
// Initialize our service with any options it requires
app.use('/service1', service(options));
// Get our initialize service to that we can bind hooks
const service1Service = app.service('/service1');
// Set up our before hooks
service1Service.before(hooks.before);
// Set up our after hooks
service1Service.after(hooks.after);
};