简体   繁体   English

使用Perl插入MySQL

[英]Inserting into MySQL with Perl

I have the following bound query in Perl. 我在Perl中有以下绑定查询。

$sth = $dbh->prepare("insert into tbl_name values(?,?)");
$sth->execute($val1, $val2);

However, what if the first coloumn in that tbl_name table is an auto-increment primary key? 但是,如果该tbl_name表中的第一个列是自动增量主键怎么办? What do I do to handle that field? 我该怎么办?

This is more of an SQL problem than a Perl one. 这比Perl更像是一个SQL问题。

What do I do to handle [an auto-increment] field? 如何处理[自动递增]栏位?

Don't specify it at all. 完全不指定它。 Explicitly name all the columns you are have values for and ignore the others. 明确命名所有您具有值的列,并忽略其他列。

That will cause them to take on their default values which, in the case of an auto-increment field, will be the next increment. 这将使它们采用默认值,如果是自动增量字段,则为下一个增量。

$sth = $dbh->prepare("insert into tbl_name (column_name) values (?)");
$sth->execute($val2);

You can give just the value of the second column, like this 您可以仅给出第二列的值,如下所示

my $sth = $dbh->prepare('INSERT INTO tbl_name (col2) VALUES (?)');
$sth->execute($val2);  

As the others have said, you just don't specify the value for the field by being explicit on which fields you're inserting, so as they said: 正如其他人所说的那样,您只是没有通过明确指出要插入的字段来指定字段的值,因此,正如他们所说:

my $sth = $dbh->prepare('INSERT INTO tbl_name (col2) VALUES (?)');
$sth->execute($val2); 

is going to be good enough. 会足够好。

I just want to add that you can use 我只想补充一点,您可以使用

$dbh->{'mysql_insertid'}

to get the id that was assigned to the row, which often comes in handy. 获取分配给该行的ID,这通常很方便。

$sth = $dbh->prepare("insert into tbl_name values(?,?)");
$sth->execute(undef, $val2);

or 要么

$sth = $dbh->prepare("insert into tbl_name (col2_name) values (?)");
$sth->execute($val2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM