How to insert and update sql using NodeJS, socket.io, postgres correctly?
I'm a kid in programming, especially NodeJS and Javascript. I learned about how to connect to PostgreSQL via Javascript using NodeJS and socket.io.
I searched and found this link http://gonzalo123.com/2012/05/07/asynchronous-queries-to-relational-databases-from-browser-with-node-js-and-socket-io/ . Followed it and worked well with select and update statement.
However, I still cannot perform with statement insert and update with the specified values. Here is my current code.
Server side:
var pg = require('pg');
var conString = "tcp://postgres:1234@localhost:5432/testdb";
var client = new pg.Client(conString);
client.connect();
var io = require('socket.io').listen(8888);
io.sockets.on('connection', function (socket) {
socket.on('sql', function (data) {
var query = client.query(data.sql, data.values);
query.on('row', function(row) {
socket.emit('sql', row);
});
});
});
Client (html):
<html>
<head></head>
<body>
<script src="http://localhost:8888/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8888');
var mobileno = '0123456789';
function sendSql(sql, values, cbk) {
socket.emit('sql', { sql: sql, values : values});
socket.on('sql', function(data){
console.log(data);
});
}
</script>
<p>
<a href="#" onclick="sendSql('select * from user', [], function(data) {console.log(data);})">Select</a>
</p>
<a href="#" onclick="sendSql('UPDATE user set mobile = 987654321 where id=12 ', [], function(data) {})">Update</a>
</p>
<p>
<a href="#" onclick="sendSql('INSERT INTO user (name) values('Michael'),[], function(data) {console.log(data);})">Insert</a>
</p>
</body>
</html>
From the above code, the Select statement works fine with all data displays in the Chrome console.
For the update operator, I can update the data in the "mobile" column with the value "987654321". But I want the value from var mobileno = '123456789';
, then I tried ...
UPDATE user set mobile = mobileno
It doesn't work and the server console says "column mobileno does not exist".
For an insert statement, I really have no idea about it. Tried to change the syntax in many ways but still can't get it to work and still get various errors.
I think someone here should have experience with this. Please kindly teach me how to use update and embed this thing in the statement correctly.
source to share