this is my first question here. I've been trying to get a column added to a database, using ExpressJS and sqlite3. Normally I use a question mark as a placeholder/parameter, but in this case I get an error. I've been struggling with this for hours but I can't get it to work. This is the error I get:
[Error: SQLITE_ERROR: near "?": syntax error] {
errno: 1,
code: 'SQLITE_ERROR'
}
Hope you guys can help me!
var scoreOfGame = req.body.game + "_Score";
db.all("ALTER TABLE Users ADD COLUMN ? INT", [scoreOfGame], (error, results) => {
if (error) {
console.log(error)
}
else {
console.log(results)
}
})
Instead of using ? as a placeholder, I rewrote it to this:
db.all(`ALTER TABLE Users ADD COLUMN ${scoreOfGame} INT`)
Related
I'm making a clear command in discord.js AND I DO KNOW THERE IS ANOTHER DUPLICATE but for some reason that DUPLICATE question doesn't solve my answer
else if(command == "clear")
{
async function clear(){
let fetched;
do {
fetched = await message.channel.messages.fetch({limit: 100});
message.channel.bulkDelete(fetched);
message.delete()
}
while(fetched.size >= 2)
}
clear();
}
and the title is the error I got
To delete messages no need to fetch them.
You can just write
message.channel.bulkDelete(100,true).then(msg=>{
console.log(`${msg.size} is deleted!`)
}).catch(err=>{
console.log(err)
})
The second parameter is to filter the 2 weeks old messages. More can be found here
I am trying to connect to a database using the code below:
import SQLite from 'react-native-sqlite-storage'
var db = SQLite.openDatabase({name : "banco.db", createFromLocation : 1}, this.successCB(), this.errorCB());
errorCB() {
this.setState({message: "I NEED SHOW THE ERROR HERE"});
}
successCB() {
this.setState({message: "SQL executed fine"});
}
How to show the error on the errorCB function?
This is in the documentation example. The error callback will get passed an argument containing the error. You are also not providing the correct value to openDatabase. You should be passing in functions, not trying to call the function.
Copy pasting the relevant parts from the documentation with comments to explain:
// Your error callback function that should take an argument that will contain your error.
errorCB(err) {
console.log("SQL Error: " + err);
// Here you can use err in your setState call.
}
openCB() {
console.log("Database OPENED");
}
// openDatabase should be passed in the functions; openCB and errorCB in this example.
var db = SQLite.openDatabase("test.db", "1.0", "Test Database", 200000, openCB, errorCB);
// What you're doing is incorrect as it's akin to doing this which is wrong.
// var db = SQLite.openDatabase("test.db", "1.0", "Test Database", 200000, openCB(), errorCB());
This is really more of a basic JavaScript question where you need to be able to read the documentation and understand how to use a given API. If you're having trouble with this, I suggest reading up about Higher-Order Functions as it's fundamental to JavaScript.
Edit: To be very direct and answer the comments; this is what your code should look like:
import SQLite from 'react-native-sqlite-storage'
var db = SQLite.openDatabase({name : "banco.db", createFromLocation : 1}, this.successCB, this.errorCB);
// Making the assumption that these are in a class,
// otherwise add the const keyword before them.
// Convert these to arrow functions instead
// so they can more easily be passed as variables.
errorCB = (err) => {
this.setState({message: err});
}
successCB = () => {
this.setState({message: "SQL executed fine"});
}
Given your comments, I'll be very direct here. If you don't understand how functions, Higher-Order Functions, and variables/values work in JavaScript, you are going to have a very difficult time with React Native. Especially so if you are unfamiliar with ES6 syntax. Go through the book in that link or one of the many other great resources for learning the fundamentals of JavaScript before tackling React Native.
I used to open SQLite using following statement
database = SQLite.openDatabase({name: 'my.db', location: 'default'}, (db) => {
db.transaction( tx => {
tx.executeSql(`CREATE TABLE IF NOT EXISTS tableName (columnNames)`);
}, error => {
this.setState({message: error});
});
}, error => {
this.setState({message: error});
});
Hope this will help!
I am new to Cucumber, and trying to write some simple tests to get started. One thing I want to test is if an element is not on the page.
In my code I do:
var myBrowser = this.browser;
menu_data.hashes().forEach(function(menuItem, idx, items) {
myBrowser
.isExisting('#' + menuItem.anchor_id, function(err, isExisting) {
if (err) {
throw err;
} else {
isExisting.should.is.isfalse;
}
});
});
Everything I have tried testing isExisting has failed. I tried using assert.isfalse(isExisting), but I get an error saying assert is not there. In fact, when I try to use any methods, like should.assert.toFalse(isExisting) throws an error saying toFalse doesn't exist.
My bad. Have you tried should.be(false)
This is due to view port being too small.
Duplicate of this WebDriver element is returning false for isVisible/waitForForVisible
I'm working on a project with the following Firebase structure:
user {
score: 0,
messages : {
key1 { name: name, text: text }
key2 { name: name, text: text }
key...
}
}
I currently have two problems. The first is determining if the user has a "messages" child, if not, then give it one (along with a score), here's the code I came up with so far:
ref.once('value', function (snapshot) {
if (!snapshot.hasChild("messages")) {
ref.set({
score: 0,
messages: 0
});
}
});
The next is retrieving and displaying the messages from the child once the data has been pushed to it like so:
ref.child("messages").on('child_added', function (snapshot) {
var message = snapshot.val();
$('#messagesDiv').prepend(message.text ": " + message.name);
});
but that doesn't seem like it's working either.
Here is the fiddle I made.
I hope you guys can help me fix this problem! The syntax looks right and I read over the docs to find most of the current code.
Thanks in advance!
Setting the initial data
Your code with hasChild seems is executed fine. It just doesn't make a lot of sense. The structure that you're adding leads to:
user {
score: 0,
messages: 0
}
Which is not the same as the structure you've drawn in your question: messages here is just a number, while you want it to be a collection of messages. In addition this change will not trigger your child_added handler, since... you're not adding a child to messages.
You've done the right thing by starting with designing a data structure. The next step is to ensure that you stick to that data structure. So if you want to add an initial message, add the message in the correct structure:
ref.once('value', function (snapshot) {
if (!snapshot.hasChild("messages")) {
ref.set({
score: 0,
messages: { 0: { name: 'puf', text: 'welcome' }}
});
}
});
If you modify the fiddle you will see that the welcome message does show up in your #messagesDiv.
I think this approach is still flawed though. Unless you are really looking to add a welcome message, there is no need to add a messages node. I would just set the score to 0 and the messages node will be added once the user enters their first message:
ref.once('value', function (snapshot) {
if (!snapshot.hasChild("messages")) {
ref.set({ score: 0 });
}
});
Adding new messages
I noticed that you also have the following code in your fiddle:
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = user;
var text = $('#messageInput').val();
// POST
ref.child("messages").set({
name: name,
text: text
});
$('#messageInput').val('');
}
});
The input handling is fine, but once again your code that modifies the Firebase data structure does not follow along with the data structure you started your question with. If we execute this code, the data structure will be:
user {
score: 0,
messages: {
name: 'NotToBrag',
text: 'asked 10 hours ago'
}
}
In case it's not obvious: this structure is missing the crucial key1 or your structure. Oh... and it has also overwritten the welcome message.
When you're adding a child node to a Firebase list, you almost always want to use push:
ref.child("messages").push({
name: name,
text: text
});
With that tiny change, the data structure becomes:
user {
score: 0,
messages: {
0: {
name: 'puf',
text: 'welcome'
},
'-Jh-aFN42nWef-FvgcfS': {
name: 'NotToBrag',
text: 'asked 10 hours ago'
}
}
}
All of these are (as usual) pretty small changes. But together they ensured that your scenario was pretty badly broken. The tricks I used to troubleshoot are incredibly basic and you'd do well to add them to your arsenal and learn to use them.
Debugging trick 1: console.log the data structure
Whenever I first get an MCVE of somebody's problem, I immediately log their data structure:
new Firebase('https://your.firebaseio.com/').once('value', function(s) {
console.log(s.val());
})
As times I might stringify the JSON:
new Firebase('https://your.firebaseio.com/').once('value', function(s) {
console.log(JSON.stringify(s.val()));
})
That last snippet is for example a great way to get the data structure for use in your question.
The snippet only shows the data structure once, so keep running this snippet every time something changes.
Debugging trick 2: remove your data
Your whole hasChild snippet seems aimed to set up your initial data structure for a user. To aid in testing, I frequently removed the data:
new Firebase('https://your.firebaseio.com/myName').remove()
And then when you run the fiddle again, you can see what your hasChild-using code does.
I often put code to clean out (or otherwise reset) my test data either at the start of my fiddles or simply run a snippet from the browser's JavaScript console.
I'm trying to perform a simple count with knex (since it seems to not be supported by bookshelf yet). The following code is working:
bookshelf.knex('hosts').count('id').then(function(total) {
res.send({
meta: {
total: total[0]['count(`id`)']
}
});
});
It just seems odd to me that I have to do total[0]['count('id')'] to get the actual result. Am I doing things right here?
Thanks!
All the results from knex.js are arrays. A query could be successful and simply return 0 results.
Also, you can alias the column directly in the column name (or count() call). Like this:
bookshelf.knex('hosts').count('id as CNT').then(function(total) {
res.send({
meta: {
total: total[0].CNT
}
});
});
Still need to get the first element, but you can reference the column as a normal JSON property.
While knex does return results as arrays, it also has a method for returning the first result, which will be an object--not an array. It's pretty simple to get straight to the count without having to rely on [0] or anything to access your count within an array. For your example, a cleaner solution could be:
bookshelf
.knex("hosts")
.count("id")
.first()
.then(function(total) {
res.send({
meta: {
total: total.count
}
});
});
code for node js
let result = await knex.count("id").from('events').first();
if (result) {
console.log(result.count);
}
this seems to work correctly and is a bit simpler
knex('Quotes').count('quoteBody')
.then((res)=>{
//console.log("rows "+JSON.stringify(res))
console.log("rowspl2 "+res[0]['count(`quoteBody`)'])
})
.catch((err)=>{
console.log("err "+err)
})
or try it like this
knex('Quotes').count('quoteBody', {as: 'rows'})
.then((res)=>{
// console.log("rows "+JSON.stringify(res))
console.log("rowsp "+res[0]['rows'])
})
.catch((err)=>{
console.log("err "+err)
})