So, I have 2 tables, that I've added per the documentation, but something weird happens whenever I try to add a row to them. The data is written into the .db file, but whenever I query it, it only returns the first row. I can still update, and read these rows normally, but any data I write to them, just doesn't update the table. It's only the first row that get's written.
I've looked over all my statements, and I know they're right, since the first statement adds it to the table, but the second doesn't. I'm using the base configuration of sqlite3 from npm, per the docs, so I don't know what I'm doing wrong.
I don't have any errors, and the expected result, is that I'm able to add as many rows as I can
db.serialize(function() {
db.run("CREATE TABLE users (userId int, user varchar(255))");
db.run("CREATE TABLE notes (userId int, uuid varchar(50), name varchar(255), noteData varchar(1024), file BLOB(21845))")
});
db.run("INSERT INTO users (userId, user) VALUES (0, 'User')")
db.run(`INSERT INTO notes (userId, uuid, name, noteData) VALUES (0, 'uuid', 'First Note','This will be readable.')`)
//This statement will add the data to the file, but the query won't read it.
db.run(`INSERT INTO notes (userId, uuid, name, noteData) VALUES (1, 'uuid2', 'First Note','This will not show.')`)
db.get("SELECT * FROM notes",[],(err,row)=>{console.log(row)})
Also, this is not an asynchronous problem. In the example, I added the last line, but it's not actually in my code. I'm requesting it minutes later, and I can confirm the text is in the database, it just decides not to read it.
Your second insertion into notes table looks like has syntax error because of using additional single-quote.
I've changed by using two single-quotes at db-fiddle.com and it's working, but i'm not sure why you don't get an exception.
INSERT INTO users (userId, user) VALUES (0, 'User');
INSERT INTO notes (userId, uuid, name, noteData) VALUES (0, 'uuid', 'First Note','This will be readable.');
INSERT INTO notes (userId, uuid, name, noteData) VALUES (1, 'uuid2', 'First Note','This won''t.');
SELECT * FROM notes;
Ref for using two single-quotes; https://www.sqlite.org/faq.html#q14
Turn out I needed to use db.all. db.get returns only the first row.
Related
I want Chack If Value exists in coulmn, If value exist do not insert to table.
If not exist insert to table a new data.
I tried this but not works..
my code in node.js
`
//add new meeting
async function addNewMeeting(meeting: Meeting): Promise<Meeting>{
const sql = `INSERT INTO meetings Values (
DEFAULT,
${meeting.meeting_code},
'${meeting.meeting_start_date}',
'${meeting.meeting_end_date}',
'${meeting.meeting_description}',
'${meeting.meeting_room}'
)`;
const result:OkPacket = await dal.execute(sql);
meeting.id = result.insertId;
return meeting;
}
`
I tried to chack if the value - '2022-10-15 07:03:42' exist or not.
If not exists insert to table a new data.
if exist send a error that cannot insert a new meeting because there is already meeting at this time.
thanks :)
You can solve this at the SQL level by using the keyword UNIQUE when defining that column in the table. This will prevent you from being able to insert duplicate values.
SQL UNIQUE
Note that this will throw an error and depending on the package you are using to connect to your database, you might need some error handling.
Alternatively in your javascript you can select all values in the column that should be unique, and then only proceed with the insertion code if there is not a match.
I'm currently learning MySQL and have learned the INSERTO INTO statement and the INSERT INTO SELECT statement.
The INSERT INTO statement works like this:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
While the INSERT INTO SELECT works like this:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
What I'm trying to do is add new values while also adding values that I already have stored in another table.
con.query("INSERT INTO vehicles (vehicleType, vehicleModel, vehicleOwner, vehicleSpawnX, vehicleSpawnY, vehicleSpawnZ)")
From the query above, I already have the vehicleOwner value stored in another table, while the other ones I've just gotten.
How can I do this? Add a VALUES statement before SELECT?
I'm using SQL Workbench 8.0 and JavaScript. Also, all the values are NOT NULL, so I can't make two different queries, unless on the first one I add temporary values that I'll update on the second one.
What I want to replace:
vehicleType -> "players"
vehicleModel -> vehicleCreate.model
vehicleOwner -> playerID FROM players table
vehicleSpawnX -> pos.x
vehicleSpawnY -> pos.y
vehicleSpawnZ -> pos.z
Thanks!
It's not possible... But you can select data and store that on variables, then you will store it in another table
You would construct a query. Your data model is a bit hard to follow since you give no examples of the data or of what you really want to do.
So let me give a simpler example. Say, you have a table with two columns for two players and you want to put the ids into a table -- but using their names. The query would look like:
insert into pairs (playerId1, playerId2)
select p1.playerId, p2.playerId
from players p1 join
players p2
on p1.name = ? and p2.name = ?;
The ? are for parameter placeholders. I assume you know to aways use parameters when passing values into a query.
I have simple table and I need to insert in to it values from array, but only values which are not exists in table and return from query inserted values, how I can do this?
I have next query, but it just inserts values:
INSERT INTO my_table(id, card_id, size)
VALUES ${myArray.map(item => `($${addDbValue(item.id, dbValues)},
$${dbValues.push(item.card_id)}::int, '24')`)}
`, dbValues)
unique is card_id
You seem to want on conflict and returning:
insert into my_table(id, card_id, size)
values (?, ?, ?)
on conflict (card_id) do nothing
returning *
The query inserts the new row, and returns the entire row (including columns that were not initially given for insert). If a row already exists with the same card_id, the insert is not performed (for this to work, you need a unique index or constraint on card_id).
Note that you should be using query parameters (as shown above) rather than concatenating variables in the query string. Have a look at the parameterized query feature of your client.
So most questions about LAST_INSERT_ID() with multiple INSERT records involve getting multiple IDs back after the insert, my question is backwards from that.
I have table foo, with a many-to-many relationship with bar, and a junction table, foo__bar. I want to INSERT a single foo record, but also an unknown quantity of bar associations, so I need the LAST_INSERT_ID() after the first INSERT statement, but multiple times:
const db = require('mysql');
...
//connection and pooling set up
let sql = `INSERT INTO foo VALUES(null, ?, ?);
INSERT INTO foo__bar((LAST_INSERT_ID(), ?), (LAST_INSERT_ID(), ?)//etc
`;
let barIds = [1,4];
let params = [name, description, barIds[0], barIds[1]];
let result = await db.query(sql, params);
This works fine if the bar table is already populated and the bar ids are valid, and I only ever do two associations per INSERT:
--table foo__bar
+------+------+
|foo_id|bar_id|
|------|------|
| 1| 1|
|------|------|
| 1| 4|
+------+------+
But what if I have multiple values/associations? Using the 'mysql' npm package, normally I could just do this and an array will be converted into ((val1, val2),(val1, val2),(val1,val1)) etc. However, for my junction table, I need val1 to be the same every time, specifically LAST_INSERT_ID(). Is this possible without having to make two async calls to the database?
Thanks
On my website I am trying to select 2 tables - tableB of which might be empty, so its not returning any results at all when tableB is empty. I hope I am explaining this properly. Any suggestions?
curatio.webdb.getAllTodoItems = function(renderFunc) {
var db = curatio.webdb.db;
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM tableA, tableB", [], renderFunc,
curatio.webdb.onError);
});
}
basically TableA has e.g. Name and Surname columns and TableB has e.g. Address details. But sometimes there is no address, and then I cannot get anything to display.
I need to basically ignore tableB if it's empty.
If tableA and tableB have the same schema, you can do something like this:
SELECT * FROM tableA
UNION
SELECT * FROM tableB
However, if they don't have the same schema, you will have to do something smarter to get the union to work.
Although your query doesn't hint at this, I still think you are probably looking for a LEFT JOIN, because I'm assuming you want to link data from two tables by a common value in a column from table B (known as the foreign key).
This query selects values of the first table, even when there's no matching data in the join table:
SELECT *
FROM `tableA` `a`
LEFT JOIN `tableB` `b`
ON `b`.`someReferenceColumnToTableA` = `a`.`theReferredColumn`
Again, this assumes you meant to join two tables by some common value, for instance:
person (table A):
- id
- name
phonenumber (table B):
- id
- person_id // this is the foreign key to table A that "links" the data
- phonenumber
If you were to use a regular JOIN (also known as INNER JOIN) then only rows are returned for when both tables have matching data.
What your original query did, however, was (implicitly) CROSS JOIN all data from both tables. Given your question edit, I hardly think this is what you were actually after.
What you are performing there is called a Cross-Product of those two tables. A cross-product is essentially every row of tableA with every row of tableB. Since tableB has no rows, the cross-product has no rows. If you want all rows of both tables, use 2 queries. I would recommend reading a basic SQL tutorial.
curatio.webdb.getAllTodoItems = function(renderFunc) {
var db = curatio.webdb.db;
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM tableA UNION ALL SELECT * FROM tableB", [], renderFunc,
curatio.webdb.onError);
});
}
It will best to explicitly use the column names in both select rather then using the *.