I'm trying to do this:
$sth = $dbi->prepare('INSERT INTO table VALUES (?, ?, ?)');
$sth->execute(
$var1,
$var2 || 'NOW()',
$var3
);
without any luck. Any ideas?
$sth = $dbi->prepare('INSERT INTO table VALUES (?, COALESCE(?, NOW()), ?)');
$sth->execute(
$var1,
$var2,
$var3
);
Functions cannot be bound parameters. MySQL will enclose them in quotes which is not valid syntax.
Your options are:
DEFAULT CURRENT_TIMESTAMP - If the field is a TIMESTAMP field you can declare it to have a default of the current time like this. This does not work for DATETIME fields.
Use perl - $now = time2str('%Y-%m-%d %T', time);
You can use the following coding also.
$sth = $dbi->prepare('INSERT INTO table VALUES (?, COALESCE(?, NOW()), ?)');
$sth->bind_param($var1,$var2,$var3);
$sth1=$sth->execute;
Related
I have these 2 variables here
name := request.FormValue("username")
pass := request.FormValue("password")
I want to insert those 2 variables into my database
db.Query("INSERT INTO `godb` (`Username`, `Password`) VALUES ( )")
I tried (name,pass) ('name','pass') ($name, $pass) , none of them work.
Hope the question is not stupid, but I've been looking for solutions online but I did't understand them. Thanks !
From Using Prepared Statements
Parameter Placeholder Syntax
The syntax for placeholder parameters in prepared statements is
database-specific. For example, comparing MySQL, PostgreSQL, and
Oracle:
MySQL PostgreSQL Oracle
===== ========== ======
WHERE col = ? WHERE col = $1 WHERE col = :col
VALUES(?, ?, ?) VALUES($1, $2, $3) VALUES(:val1, :val2, :val3)
You tried PostgreSQL syntax but you use MySQL.
query should be in this format
db.Query("INSERT INTO table ($1, $2) VALUES (column1, column2)", value1, value2)
in your case something like that
db.Query("INSERT INTO godb ($1, $2) VALUES (username, password)", name, pass)
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.
I got this exception while using one of the answers from stackoverflow.
You can't specify target table 'tablename' for update in FROM clause
This is my query and am using JSP to pass queries:
String queryString = "INSERT INTO tablename(SL_No,candidate,phone,pan,mailid)
VALUES(SELECT (MAX(SL_No)+1 newSL_No from tablename), ?, ?, ?, ? ))";
Thanks in advance.
INSERT INTO tablename(SL_No,candidate,phone,pan,mailid)
select MAX(SL_No) + 1, ?, ?, ?, ?
from tablename
But actually it looks like you could just use the auto-increment of the SQL engine to do MAX(SL_No) + 1. If you change to column to that then your statement would be
INSERT INTO tablename(candidate,phone,pan,mailid)
values (?, ?, ?, ?)
I currently have code for perl that looks like this:
#valid = grep { defined($column_mapping{ $headers[$_] }) } 0 .. $#headers;
...
my $sql = sprintf 'INSERT INTO tablename ( %s ) VALUES ( %s )',
join( ',', map { $column_mapping{$_} } #headers[#valid] ),
join( ',', ('?') x scalar #valid);
my $sth = $dbh->prepare($sql);
...
my #row = split /,/, <INPUT>;
$sth->execute( #row[#valid] );
(Taken from mob's answer to a previous question.)
That is basically dynamically building a sql insert statement from csv data, and only allowing the csv data with proper headers from my column mapping to be picked.
I have been looking for examples on how to do an insert statment with multiple rows of data at once.
My perl script needs to run around a few hundred million insert statments, and doing it one at a time seems really slow, especially since the server I am running it on only has 6gb of ram and a slowish internet connection.
Is there a way I can upload more than 1 row at a time of data? So one insert statment uploads maybe 50 rows, or 100 rows at once? I cant find out how with perl DBI.
my $sql_values = join( ' ', ('(?, ?, ?)') x scalar(#array) );
As said before, then you can just flatten it.
You can insert multiple rows at once with the same syntax as in regular SQL, but you need to build your INSERT statemtent properly with Perl. Perl's slice() may help you:
Suppose you have 7 rows of data and want to insert them in chunks of 3 rows. "Regular" SQL would be like so:
insert into T (col1, col2) values ( 1, 2), ( 3, 4), ( 5, 6);
insert into T (col1, col2) values ( 7, 8), ( 9,10), (11,12);
insert into T (col1, col2) values (13,14);
Let's suppose your perl structure is like this:
my $values = [ [1,2], [3,4], ..., [13,14] ];
If it's not, bring it into this shape. Now:
use constant CHUNKSIZE => 3;
my $stmt = sprintf( 'insert into T (col1, col2) values %s',
join(',', '(?,?)' x CHUNKSIZE) );
# $stmt is now 'insert into T (col1, col2) values (?,?),(?,?),(?,?)'
my $sth = $dbh->prepare($stmt);
while( my #chunk = splice( #{$values}, 0, CHUNKSIZE ) ) {
# #chunk has 3 elements (rows), or less for the last chunk
if (scalar #chunk == CHUNKSIZE) {
$sth->execute( #chunk ); # inserts 3 rows at once
} else {
# build and prepare a new statement for the remaining rows.
# in our sample there is only 1 remaining row.
$stmt = sprintf( 'insert into T (col1, col2) values %s',
join(',', '(?,?)' x scalar #chunk) );
$sth = $dbh->prepare($stmt);
$sth->execute( #chunk ); # inserts the last row
}
}
I have 2 insert queries that I need to execute. each query will insert data in a different table. The first query has ON DUPLICATE KEY UPDATE clause. What I need to do is to prevent the second query from running is the first one cause an update due to a DUPLICATE KEY.
here is my code currently.
$insertEvent = $db->processQuery('INSERT INTO calendar_events (start_on, end_on, subject, owner_id, created_by, phone_call_id, status )
VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE start_on = ?, end_on =?, status = ? ',
array($start, $end, $subject, $owner, $created_by, $phone_call_id, $status, $start, $end, $status) );
$event_id = $db->lastinsertid();
$insertEvent2 = $db->processQuery('INSERT INTO calendar_attendees (event_id, owner_id) VALUE (?, ?)', array($event_id, $owner));
I only want to execute $insertEvent2 only if $insertEvent created a new record otherise ignore the second statement.
Thanks
I believe you can use INSERT IGNORE syntax on your second INSERT, so that your query will look like
INSERT IGNORE INTO calendar_attendees (event_id, owner_id) VALUES (?, ?)
Make sure that you have a UNIQE constraint on (event_id, owner_id).
BTW you have a typo in your second insert. It should be VALUES instead of VALUE.