I am trying to store latitude and longitude information in MySQL. I am using Ruby to parse the latitude and longitude data. They are parsed separately and then combined into a string variable. So if I have:
latitude = 43.78219.to_s
longitude = -75.00326.to_s
location = latitude + " " + longitude # => "43.78219 -75.00326"
I have a table in MySQL to store this data, and the data type is set to String varchar. The problem is that when I insert the location string into the table, MySQL performs a math operation and subtracts the two numbers in the string. Then I'm like Whaaaaaaaaa???????
So it ends up storing -31.22107 as the location. Am I doing something wrong?
Here is the query I'm using
db.query("insert into StationCapacityStatus
(city_id, station_id, location, empty_docks, nonempty_docks, timestamp)
values(
23,
#{$station_number},
#{location},
#{$empty_docks},
#{$nonempty_docks},
#{$datetime}
)"
)
You're not quoting the location so MySQL's sees a plain 43.78219 -75.00326 inside the VALUES and interprets it as a floating point expression. You should use quote method to properly escape the strings as well:
db.query("insert into StationCapacityStatus
(city_id, station_id, location, empty_docks, nonempty_docks, timestamp)
values(
23,
#{$station_number},
'#{db.quote(location)}',
#{$empty_docks},
#{$nonempty_docks},
#{$datetime}
)"
)
You should also switch to prepared statements with bound values if possible:
sth = db.prepare('insert into StationCapacityStatus (city_id, station_id, location, empty_docks, nonempty_docks, timestamp) values (?, ?, ?, ?, ?, ?)')
sth.execute(23, $station_number, location, $empty_docks, $nonempty_docks, $datetime)
Related
I'm trying to insert data into MySQL via Express, the database table is created as such:
create table foods (name VARCHAR(100), typval DECIMAL(8, 2), unit VARCHAR(50), calories DECIMAL(5, 2), carbs DECIMAL(5, 2), fat DECIMAL(5,2), protein DECIMAL(5, 2), salt DECIMAL(5, 2), sugar DECIMAL(5, 2));
I have a form which collects user data and the function to post looks something like this:
app.post("/addnewfood", function (req,res) {
console.log(req.body.name, req.body.typval, req.body.unit, req.body.calories, req.body.carbs, req.body.fat, req.body.protein, req.body.salt, req.body.sugar);
// saving data in database
let sqlquery = "INSERT INTO foods (name, typval, unit, calories, carbs, fat, protein, salt, sugar) VALUES (?,?)";
// execute sql query
let newrecord = [req.body.name, req.body.typval, req.body.unit, req.body.calories, req.body.carbs, req.body.fat, req.body.protein, req.body.salt, req.body.sugar];
db.query(sqlquery, newrecord, (err, result) => {
if (err) {
return console.error(err.message);
}else
res.send("New" + " " + req.body.name + " was added to the database.");
});
});
I'm not sure where I'm going wrong since I counted there's 9 different fields I need to fill in for the 9 different columns. I've checked the commas and I can't see anything out of place.
When I try to enter data like: "McDonalds Hamburger, 1.0, Burger, 100.00, 10.00, 10.00, 10.00, 1.0, 10.00"
The console.log prints it out fine and it should work however, I get:
ER_WRONG_VALUE_COUNT_ON_ROW: Column count doesn't match value count at row 1
Help?
Your INSERT query needs a placeholder for every column you insert. You only have two placeholders -- two ? items -- here.
VALUES (?,?)
You need nine, one for each column.
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
This table has many parameters, and when i do insert it's like this, (... is for demo propose)
const sqlCmd = `insert into Consumer (key, secret, ..., version)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
try {
const param = [myTable.key, myTable.secret, ..., myTable.version];
return await dbPool.execSqlCmd(sqlCmd, param)
}
Is there a way to avoid so many ?s ?
In SQL, you use one ? parameter placeholder for each scalar value you want to pass to the SQL statement. No more, no less.
If you want fewer ? placeholders, then you must pass fewer parameters. You can do this by:
Omitting some columns from the INSERT statement. The row inserted will use the DEFAULT value declared for the column, or else NULL if there is no default.
Using a constant expression in the VALUES clause for some columns, instead of a parameter. I mean this can be a constant literal, like a numeric or string or date, or it can be an expression or function, which will be evaluated, and the resulting value used for the INSERT.
error in insert operation is the error I am getting when I run this code please somebody help me in finding out the error. I am trying to create a student database in flask sqlalchemy
One way is to define variables names and then pass them.
engine.execute('INSERT INTO person (name, balance) VALUES (:name, :balance)', name = 'Joe', balance = 100)
Reference : https://code-maven.com/slides/python-programming/sqlalchemy-engine-insert
I am trying to insert data into a MySQL database:
$response = $client->fql->query(
query => '
SELECT name, email, birthday, username, first_name, last_name, pic
FROM user
WHERE uid = me()
',
);
print join "\n Name:", sort map { $_->{name} } #$response;
$dbh->do("
INSERT INTO Users(SNo,Name,Email,Birthday,UserName,FirstName,LastName)
VALUES(1,
sort map { $_->{name} } #$response,
'imm\#gmail.com',
'1987/12/10',
'imm',
'imm',
'Dee')
");
$dbh->disconnect();
used the mysql query in one line.
This above print statement is printing the name correctly but why the above sql insert statement is not working?
I connect the db and after that i am receiving the value and printing in the browser is working.
Why does the mysql statement not accept the value?
When inserting the database is not working?
You should have a look at the official doc
and specially this :
# INSERT some data into 'foo'. We are using $dbh->quote() for
# quoting the name.
$dbh->do("INSERT INTO foo VALUES (1, " . $dbh->quote("Tim") . ")");
# Same thing, but using placeholders
$dbh->do("INSERT INTO foo VALUES (?, ?)", undef, 2, "Jochen");
I have an INSERT INTO which works fine with the parameters as constants:
INSERT INTO FinalValidityCodes
(tblReceivedSamplersID, Substudy, Location, FinalValidityCode, DateTimeProcessed)
SELECT ID, true, 'I', 0, now()
FROM tblReceivedSamplers
WHERE (SampleID = ?)
This would affect 1 row (as expected)
Yet if I change the query to use parameters it will allow it to run but will never affect any rows.
INSERT INTO FinalValidityCodes
(tblReceivedSamplersID, Substudy, Location, FinalValidityCode, DateTimeProcessed)
SELECT ID, ?, ?, ?, ?
FROM tblReceivedSamplers
WHERE (SampleID = ?)
What is the difference and why, when I use parameters, does the Insert, seemingly, fail?
Edit:
SampleID is a text datatype.
It looks like the purpose of that INSERT is to add a single row to FinalValidityCodes with values for 5 fields. However, 4 of those values will be supplied directly by query parameters, and ID/tblReceivedSamplersID will be derived from another parameter.
So I would try a DLookup() expression to get the ID (using the parameter for SampleID), and insert that value along with the other 4 parameter values. Here is an untested guess.
INSERT INTO FinalValidityCodes (
tblReceivedSamplersID,
Substudy,
Location,
FinalValidityCode,
DateTimeProcessed
)
VALUES (
DLookup("ID", "tblReceivedSamplers", "SampleID ='" & param1 & "'"),
param2,
param3,
param4,
param5
);