DBI with DBD::mysql
DBI Interface
DBI/DBD Information
DBI InterfacePortable DBI Methods and Attributes
| Method/Attribute | Description |
connect | Establishes a connection to a database server. |
disconnect | Disconnects from the database server. |
prepare | Prepares an SQL statement for execution. |
execute | Executes prepared statements. |
do | Prepares and executes an SQL statement. |
quote | Quotes string or BLOB values to be inserted.
|
fetchrow_array | Fetches the next row as an array of fields. |
fetchrow_arrayref | Fetches next row as a reference array of fields. |
fetchrow_hashref | Fetches next row as a reference to a hashtable. |
fetchall_arrayref | Fetches all data as an array of arrays. |
finish | Finishes a statement and lets the system free resources. |
rows | Returns the number of rows affected. |
data_sources | Returns an array of databases available on localhost. |
ChopBlanks | Controls whether fetchrow_* methods trim spaces.
|
NUM_OF_PARAMS | The number of placeholders in the prepared statement. |
NULLABLE | Which columns can be NULL.
|
trace | Perform tracing for debugging. |
MySQL-specific Methods and Attributes
| Method/Attribute | Description |
mysql_insertid | The latest AUTO_INCREMENT value.
|
is_blob | Which columns are BLOB values.
|
is_key | Which columns are keys. |
is_num | Which columns are numeric. |
is_pri_key | Which columns are primary keys. |
is_not_null | Which columns CANNOT be NULL. See NULLABLE.
|
length | Maximum possible column sizes. |
max_length | Maximum column sizes actually present in result. |
NAME | Column names. |
NUM_OF_FIELDS | Number of fields returned. |
table | Table names in returned set. |
type | All column types. |
The Perl methods are described in more detail in the following sections. Variables used for method return values have these meanings:
$dbh
$sth
$rc
$rv
Portable DBI Methods and Attributes
connect($data_source, $username, $password)
connect method to make a database connection to the data
source. The $data_source value should begin with
DBI:driver_name:.
Example uses of connect with the DBD::mysql driver:
$dbh = DBI->connect("DBI:mysql:$database", $user, $password);
$dbh = DBI->connect("DBI:mysql:$database:$hostname",
$user, $password);
$dbh = DBI->connect("DBI:mysql:$database:$hostname:$port",
$user, $password);
If the user name and/or password are undefined, DBI uses the
values of the DBI_USER and DBI_PASS environment variables,
respectively. If you don't specify a hostname, it defaults to
'localhost'. If you don't specify a port number, it defaults to the
default MySQL port (3306).
As of Msql-Mysql-modules Version 1.2009,
the $data_source value allows certain modifiers:
mysql_read_default_file=file_name
mysql_read_default_group=group_name
[client] group. By specifying the mysql_read_default_group
option, the default group becomes the [group_name] group.
mysql_compression=1
mysql_socket=/path/to/socket
DBI script, you can take them from the user's `~/.my.cnf'
option file instead by writing your connect call like this:
$dbh = DBI->connect("DBI:mysql:$database"
. ";mysql_read_default_file=$ENV{HOME}/.my.cnf",
$user, $password);
This call will read options defined for the [client] group in the
option file. If you wanted to do the same thing but use options specified
for the [perl] group as well, you could use this:
$dbh = DBI->connect("DBI:mysql:$database"
. ";mysql_read_default_file=$ENV{HOME}/.my.cnf"
. ";mysql_read_default_group=perl",
$user, $password);
disconnect
disconnect method disconnects the database handle from the database.
This is typically called right before you exit from the program.
Example:
$rc = $dbh->disconnect;
prepare($statement)
($sth), which you can use to invoke
the execute method.
Typically you handle SELECT statements (and SELECT-like
statements such as SHOW, DESCRIBE, and EXPLAIN) by
means of prepare and execute. Example:
$sth = $dbh->prepare($statement)
or die "Can't prepare $statement: $dbh->errstr\n";
If you want to read big results to your client you can tell Perl to use
mysql_use_result() with:
my $sth = $dbh->prepare($statement { "mysql_use_result" => 1});
execute
execute method executes a prepared statement. For
non-SELECT statements, execute returns the number of rows
affected. If no rows are affected, execute returns "0E0",
which Perl treats as zero but regards as true. If an error occurs,
execute returns undef. For SELECT statements,
execute only starts the SQL query in the database; you need to use one
of the fetch_* methods described here to retrieve the data.
Example:
$rv = $sth->execute
or die "can't execute the query: " . $sth->errstr;
do($statement)
do method prepares and executes an SQL statement and returns the
number of rows affected. If no rows are affected, do returns
"0E0", which Perl treats as zero but regards as true. This method is
generally used for non-SELECT statements that cannot be prepared in
advance (due to driver limitations) or that do not need to be executed more
than once (inserts, deletes, etc.). Example:
$rv = $dbh->do($statement)
or die "Can't execute $statement: $dbh- >errstr\n";
Generally the 'do' statement is much faster (and is preferable)
than prepare/execute for statements that don't contain parameters.
quote($string)
quote method is used to "escape" any special characters contained in
the string and to add the required outer quotation marks.
Example:
$sql = $dbh->quote($string)
fetchrow_array
while(@row = $sth->fetchrow_array) {
print qw($row[0]\t$row[1]\t$row[2]\n);
}
fetchrow_arrayref
while($row_ref = $sth->fetchrow_arrayref) {
print qw($row_ref->[0]\t$row_ref->[1]\t$row_ref->[2]\n);
}
fetchrow_hashref
while($hash_ref = $sth->fetchrow_hashref) {
print qw($hash_ref->{firstname}\t$hash_ref->{lastname}\t\
$hash_ref->{title}\n);
}
fetchall_arrayref
my $table = $sth->fetchall_arrayref
or die "$sth->errstr\n";
my($i, $j);
for $i ( 0 .. $#{$table} ) {
for $j ( 0 .. $#{$table->[$i]} ) {
print "$table->[$i][$j]\t";
}
print "\n";
}
finish
$rc = $sth->finish;
rows
SELECT execute
statement. Example:
$rv = $sth->rows;
NULLABLE
NULL values.
The possible values for each array element are 0 or the empty string if the
column cannot be NULL, 1 if it can, and 2 if the column's NULL
status is unknown.
Example:
$null_possible = $sth->{NULLABLE};
NUM_OF_FIELDS
SELECT or SHOW FIELDS
statement. You may use this for checking whether a statement returned a
result: A zero value indicates a non-SELECT statement like
INSERT, DELETE, or UPDATE.
Example:
$nr_of_fields = $sth->{NUM_OF_FIELDS};
data_sources($driver_name)
'localhost'.
Example:
@dbs = DBI->data_sources("mysql");
ChopBlanks
fetchrow_* methods will chop
leading and trailing blanks from the returned values.
Example:
$sth->{'ChopBlanks'} =1;
trace($trace_level)
trace($trace_level, $trace_filename)
trace method enables or disables tracing. When invoked as a
DBI class method, it affects tracing for all handles. When invoked as
a database or statement handle method, it affects tracing for the given
handle (and any future children of the handle). Setting $trace_level
to 2 provides detailed trace information. Setting $trace_level to 0
disables tracing. Trace output goes to the standard error output by
default. If $trace_filename is specified, the file is opened in
append mode and output for all traced handles is written to that
file. Example:
DBI->trace(2); # trace everything
DBI->trace(2,"/tmp/dbi.out"); # trace everything to
# /tmp/dbi.out
$dth->trace(2); # trace this database handle
$sth->trace(2); # trace this statement handle
You can also enable DBI tracing by setting the DBI_TRACE
environment variable. Setting it to a numeric value is equivalent to calling
DBI->(value). Setting it to a pathname is equivalent to calling
DBI->(2,value).
MySQL-specific Methods and Attributes
The methods shown here are MySQL-specific and not part of the
DBI standard. Several of them are now deprecated:
is_blob, is_key, is_num, is_pri_key,
is_not_null, length, max_length, and table.
Where DBI-standard alternatives exist, they are noted here:
mysql_insertid
AUTO_INCREMENT feature of MySQL, the new
auto-incremented values will be stored here.
Example:
$new_id = $sth->{mysql_insertid};
With old versions of the DBI interface, you could use $sth->{'insertid'}.
is_blob
BLOB.
Example:
$keys = $sth->{is_blob};
is_key
$keys = $sth->{is_key};
is_num
$nums = $sth->{is_num};
is_pri_key
$pri_keys = $sth->{is_pri_key};
is_not_null
NULL
values.
Example:
$not_nulls = $sth->{is_not_null};
is_not_null is deprecated; it is preferable to use the
NULLABLE attribute (described above), because that is a DBI standard.
length
max_length
length array indicates the maximum possible sizes that each column may
be (as declared in the table description). The max_length array
indicates the maximum sizes actually present in the result table. Example:
$lengths = $sth->{length};
$max_lengths = $sth->{max_length};
NAME
$names = $sth->{NAME};
table
$tables = $sth->{table};
type
$types = $sth->{type};
| Posted by Ankita Singh on Sunday May 4 2003, @12:53pm | [Delete] [Edit] |
When you are accessing a MySQL database off of another server using
$dbh = DBI->connect("DBI:mysql:$database:$hostname",
$user, $password);
make sure that you have granted rights to your user@yourdomain otherwise it will deny access because it will grant rights as user@hostname if not specified.
| Posted by David Cumming on Sunday June 8 2003, @6:19pm | [Delete] [Edit] |
The {mysql_insertid} won't work if you use INSERT DELAYED ... to insert your data.
| Posted by David Carter on Tuesday June 10 2003, @9:16am | [Delete] [Edit] |
When trying to get the column types from a table returned by a query the below method does not return a referance:
$types = $sth->{type};
However this modification works fine:
$types = $sth->{TYPE};