⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mysql.pm

📁 Astercon2 开源软交换 2.2.0
💻 PM
📖 第 1 页 / 共 4 页
字号:
			: split /,/, $typemod||'';      # no quotes, plain list	  s/''/'/g for @type_params;                # undo doubling of quotes	  my @type_attr= split / /, $attr||'';  	$info->{DATA_TYPE}= SQL_VARCHAR();    if ($basetype =~ /^(char|varchar|\w*text|\w*blob)/)    {      $info->{DATA_TYPE}= SQL_CHAR() if $basetype eq 'char';      if ($type_params[0])      {        $info->{COLUMN_SIZE} = $type_params[0];      }      else      {        $info->{COLUMN_SIZE} = 65535;        $info->{COLUMN_SIZE} = 255        if $basetype =~ /^tiny/;        $info->{COLUMN_SIZE} = 16777215   if $basetype =~ /^medium/;        $info->{COLUMN_SIZE} = 4294967295 if $basetype =~ /^long/;      }    }	  elsif ($basetype =~ /^(binary|varbinary)/)    {      $info->{COLUMN_SIZE} = $type_params[0];	    # SQL_BINARY & SQL_VARBINARY are tempting here but don't match the	    # semantics for mysql (not hex). SQL_CHAR &  SQL_VARCHAR are correct here.	    $info->{DATA_TYPE} = ($basetype eq 'binary') ? SQL_CHAR() : SQL_VARCHAR();    }    elsif ($basetype =~ /^(enum|set)/)    {	    if ($basetype eq 'set')      {		    $info->{COLUMN_SIZE} = length(join ",", @type_params);	    }	    else      {        my $max_len = 0;        length($_) > $max_len and $max_len = length($_) for @type_params;        $info->{COLUMN_SIZE} = $max_len;	    }	    $info->{"mysql_values"} = \@type_params;    }    elsif ($basetype =~ /int/)    {       # big/medium/small/tiny etc + unsigned?	    $info->{DATA_TYPE} = SQL_INTEGER();	    $info->{NUM_PREC_RADIX} = 10;	    $info->{COLUMN_SIZE} = $type_params[0];    }    elsif ($basetype =~ /^decimal/)    {      $info->{DATA_TYPE} = SQL_DECIMAL();      $info->{NUM_PREC_RADIX} = 10;      $info->{COLUMN_SIZE}    = $type_params[0];      $info->{DECIMAL_DIGITS} = $type_params[1];    }    elsif ($basetype =~ /^(float|double)/)    {	    $info->{DATA_TYPE} = ($basetype eq 'float') ? SQL_FLOAT() : SQL_DOUBLE();	    $info->{NUM_PREC_RADIX} = 2;	    $info->{COLUMN_SIZE} = ($basetype eq 'float') ? 32 : 64;    }    elsif ($basetype =~ /date|time/)    {       # date/datetime/time/timestamp	    if ($basetype eq 'time' or $basetype eq 'date')      {		    #$info->{DATA_TYPE}   = ($basetype eq 'time') ? SQL_TYPE_TIME() : SQL_TYPE_DATE();        $info->{DATA_TYPE}   = ($basetype eq 'time') ? SQL_TIME() : SQL_DATE();         $info->{COLUMN_SIZE} = ($basetype eq 'time') ? 8 : 10;      }	    else      {        # datetime/timestamp        #$info->{DATA_TYPE}     = SQL_TYPE_TIMESTAMP();		    $info->{DATA_TYPE}        = SQL_TIMESTAMP();		    $info->{SQL_DATA_TYPE}    = SQL_DATETIME();        $info->{SQL_DATETIME_SUB} = $info->{DATA_TYPE} - ($info->{SQL_DATA_TYPE} * 10);        $info->{COLUMN_SIZE}      = ($basetype eq 'datetime') ? 19 : $type_params[0] || 14;	    }	    $info->{DECIMAL_DIGITS}= 0; # no fractional seconds    }    elsif ($basetype eq 'year')    {	      # no close standard so treat as int	    $info->{DATA_TYPE}      = SQL_INTEGER();	    $info->{NUM_PREC_RADIX} = 10;	    $info->{COLUMN_SIZE}    = 4;	  }	  else    {	    Carp::carp("column_info: unrecognized column type '$basetype' of $table_id.$row->{field} treated as varchar");    }    $info->{SQL_DATA_TYPE} ||= $info->{DATA_TYPE};    #warn Dumper($info);  }  my $sponge = DBI->connect("DBI:Sponge:", '','')    or (  $dbh->{mysql_server_prepare}= $mysql_server_prepare_save &&          return $dbh->DBI::set_err($DBI::err, "DBI::Sponge: $DBI::errstr"));  my $sth = $sponge->prepare("column_info $table", {      rows          => [ map { [ @{$_}{@names} ] } values %col_info ],      NUM_OF_FIELDS => scalar @names,      NAME          => \@names,      }) or  return ($dbh->{mysql_server_prepare}= $mysql_server_prepare_save &&          $dbh->DBI::set_err($sponge->err(), $sponge->errstr()));  $dbh->{mysql_server_prepare}= $mysql_server_prepare_save;  return $sth;}sub primary_key_info {  my ($dbh, $catalog, $schema, $table) = @_;  $dbh->{mysql_server_prepare}||= 0;  my $mysql_server_prepare_save= $dbh->{mysql_server_prepare};  my $table_id = $dbh->quote_identifier($catalog, $schema, $table);  my @names = qw(      TABLE_CAT TABLE_SCHEM TABLE_NAME COLUMN_NAME KEY_SEQ PK_NAME      );  my %col_info;  local $dbh->{FetchHashKeyName} = 'NAME_lc';  my $desc_sth = $dbh->prepare("SHOW KEYS FROM $table_id");  my $desc= $dbh->selectall_arrayref($desc_sth, { Columns=>{} });  my $ordinal_pos = 0;  for my $row (grep { $_->{key_name} eq 'PRIMARY'} @$desc)  {    $col_info{ $row->{column_name} }= {      TABLE_CAT   => $catalog,      TABLE_SCHEM => $schema,      TABLE_NAME  => $table,      COLUMN_NAME => $row->{column_name},      KEY_SEQ     => $row->{seq_in_index},      PK_NAME     => $row->{key_name},    };  }  my $sponge = DBI->connect("DBI:Sponge:", '','')    or      ($dbh->{mysql_server_prepare}= $mysql_server_prepare_save &&      return $dbh->DBI::set_err($DBI::err, "DBI::Sponge: $DBI::errstr"));  my $sth= $sponge->prepare("primary_key_info $table", {      rows          => [ map { [ @{$_}{@names} ] } values %col_info ],      NUM_OF_FIELDS => scalar @names,      NAME          => \@names,      }) or        ($dbh->{mysql_server_prepare}= $mysql_server_prepare_save &&        return $dbh->DBI::set_err($sponge->err(), $sponge->errstr()));  $dbh->{mysql_server_prepare}= $mysql_server_prepare_save;  return $sth;}sub foreign_key_info {    my ($dbh,        $pk_catalog, $pk_schema, $pk_table,        $fk_catalog, $fk_schema, $fk_table,       ) = @_;    # INFORMATION_SCHEMA.KEY_COLUMN_USAGE was added in 5.0.6    my ($maj, $min, $point) = _version($dbh);    return if $maj < 5 || ($maj == 5 && $point < 6);    my $sql = <<'EOF';SELECT NULL AS PKTABLE_CAT,       A.REFERENCED_TABLE_SCHEMA AS PKTABLE_SCHEM,       A.REFERENCED_TABLE_NAME AS PKTABLE_NAME,       A.REFERENCED_COLUMN_NAME AS PKCOLUMN_NAME,       A.TABLE_CATALOG AS FKTABLE_CAT,       A.TABLE_SCHEMA AS FKTABLE_SCHEM,       A.TABLE_NAME AS FKTABLE_NAME,       A.COLUMN_NAME AS FKCOLUMN_NAME,       A.ORDINAL_POSITION AS KEY_SEQ,       NULL AS UPDATE_RULE,       NULL AS DELETE_RULE,       A.CONSTRAINT_NAME AS FK_NAME,       NULL AS PK_NAME,       NULL AS DEFERABILITY,       NULL AS UNIQUE_OR_PRIMARY  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE A,       INFORMATION_SCHEMA.TABLE_CONSTRAINTS B WHERE A.TABLE_SCHEMA = B.TABLE_SCHEMA AND A.TABLE_NAME = B.TABLE_NAME   AND A.CONSTRAINT_NAME = B.CONSTRAINT_NAME AND B.CONSTRAINT_TYPE IS NOT NULLEOF    my @where;    my @bind;    # catalogs are not yet supported by MySQL#    if (defined $pk_catalog) {#        push @where, 'A.REFERENCED_TABLE_CATALOG = ?';#        push @bind, $pk_catalog;#    }    if (defined $pk_schema) {        push @where, 'A.REFERENCED_TABLE_SCHEMA = ?';        push @bind, $pk_schema;    }    if (defined $pk_table) {        push @where, 'A.REFERENCED_TABLE_NAME = ?';        push @bind, $pk_table;    }#    if (defined $fk_catalog) {#        push @where, 'A.TABLE_CATALOG = ?';#        push @bind,  $fk_schema;#    }    if (defined $fk_schema) {        push @where, 'A.TABLE_SCHEMA = ?';        push @bind,  $fk_schema;    }    if (defined $fk_table) {        push @where, 'A.TABLE_NAME = ?';        push @bind,  $fk_table;    }    if (@where) {        $sql .= ' AND ';        $sql .= join ' AND ', @where;    }    $sql .= " ORDER BY A.TABLE_SCHEMA, A.TABLE_NAME, A.ORDINAL_POSITION";    local $dbh->{FetchHashKeyName} = 'NAME_uc';    my $sth = $dbh->prepare($sql);    $sth->execute(@bind);    return $sth;}sub _version {    my $dbh = shift;    return        $dbh->get_info($DBI::Const::GetInfoType::GetInfoType{SQL_DBMS_VER})            =~ /(\d+)\.(\d+)\.(\d+)/;}##################### get_info()# Generated by DBI::DBD::Metadatasub get_info {    my($dbh, $info_type) = @_;    require DBD::mysql::GetInfo;    my $v = $DBD::mysql::GetInfo::info{int($info_type)};    $v = $v->($dbh) if ref $v eq 'CODE';    return $v;}package DBD::mysql::st; # ====== STATEMENT ======use strict;1;__END__=pod=head1 NAMEDBD::mysql - MySQL driver for the Perl5 Database Interface (DBI)=head1 SYNOPSIS    use DBI;    $dsn = "DBI:mysql:database=$database;host=$hostname;port=$port";    $dbh = DBI->connect($dsn, $user, $password);    $drh = DBI->install_driver("mysql");    @databases = DBI->data_sources("mysql");       or    @databases = DBI->data_sources("mysql",      {"host" => $host, "port" => $port, "user" => $user, password => $pass});    $sth = $dbh->prepare("SELECT * FROM foo WHERE bla");       or    $sth = $dbh->prepare("LISTFIELDS $table");       or    $sth = $dbh->prepare("LISTINDEX $table $index");    $sth->execute;    $numRows = $sth->rows;    $numFields = $sth->{'NUM_OF_FIELDS'};    $sth->finish;    $rc = $drh->func('createdb', $database, $host, $user, $password, 'admin');    $rc = $drh->func('dropdb', $database, $host, $user, $password, 'admin');    $rc = $drh->func('shutdown', $host, $user, $password, 'admin');    $rc = $drh->func('reload', $host, $user, $password, 'admin');    $rc = $dbh->func('createdb', $database, 'admin');    $rc = $dbh->func('dropdb', $database, 'admin');    $rc = $dbh->func('shutdown', 'admin');    $rc = $dbh->func('reload', 'admin');=head1 EXAMPLE  #!/usr/bin/perl  use strict;  use DBI();  # Connect to the database.  my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost",                         "joe", "joe's password",                         {'RaiseError' => 1});  # Drop table 'foo'. This may fail, if 'foo' doesn't exist.  # Thus we put an eval around it.  eval { $dbh->do("DROP TABLE foo") };  print "Dropping foo failed: $@\n" if $@;  # Create a new table 'foo'. This must not fail, thus we don't  # catch errors.  $dbh->do("CREATE TABLE foo (id INTEGER, name VARCHAR(20))");  # 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");  # Now retrieve data from the table.  my $sth = $dbh->prepare("SELECT * FROM foo");  $sth->execute();  while (my $ref = $sth->fetchrow_hashref()) {    print "Found a row: id = $ref->{'id'}, name = $ref->{'name'}\n";  }  $sth->finish();  # Disconnect from the database.  $dbh->disconnect();=head1 DESCRIPTIONB<DBD::mysql> is the Perl5 Database Interface driver for the MySQLdatabase. In other words: DBD::mysql is an interface between the Perlprogramming language and the MySQL programming API that comes withthe MySQL relational database management system. Most functionsprovided by this programming API are supported. Some rarely usedfunctions are missing, mainly because noone ever requestedthem. :-)In what follows we first discuss the use of DBD::mysql,because this is what you will need the most. For installation, see thesections on L<INSTALLATION>, and L<WIN32 INSTALLATION>below. See L<EXAMPLE> for a simple example above.From perl you activate the interface with the statement    use DBI;After that you can connect to multiple MySQL database serversand send multiple queries to any of them via a simple object orientedinterface. Two types of objects are available: database handles andstatement handles. Perl returns a database handle to the connectmethod like so:  $dbh = DBI->connect("DBI:mysql:database=$db;host=$host",		      $user, $password, {RaiseError => 1});Once you have connected to a database, you can can execute SQLstatements with:  my $query = sprintf("INSERT INTO foo VALUES (%d, %s)",		      $number, $dbh->quote("name"));  $dbh->do($query);See L<DBI(3)> for details on the quote and do methods. An alternativeapproach is  $dbh->do("INSERT INTO foo VALUES (?, ?)", undef,	   $number, $name);in which case the quote method is executed automatically. See alsothe bind_param method in L<DBI(3)>. See L<DATABASE HANDLES> belowfor more details on database handles.If you want to retrieve results, you need to create a so-calledstatement handle with:  $sth = $dbh->prepare("SELECT * FROM $table");  $sth->execute();This statement handle can be used for multiple things. First of allyou can retreive a row of data:  my $row = $sth->fetchrow_hashref();If your table has columns ID and NAME, then $row will be hash ref withkeys ID and NAME. See L<STATEMENT HANDLES> below for more details onstatement handles.But now for a more formal approach:=head2 Class Methods=over=item B<connect>    use DBI;    $dsn = "DBI:mysql:$database";    $dsn = "DBI:mysql:database=$database;host=$hostname";    $dsn = "DBI:mysql:database=$database;host=$hostname;port=$port";    $dbh = DBI->connect($dsn, $user, $password);A C<database> must always be specified.=over=item host=item portThe hostname, if not specified or specified as '' or 'localhost', willdefault to a MySQL server running on the local machine using the default forthe UNIX socket. To connect to a MySQL server on the local machine via TCP,you must specify the loopback IP address (127.0.0.1) as the host.Should the MySQL server be running on a non-standard port number,you may explicitly state the port number to connect to in the C<hostname>argument, by concatenating the I<hostname> and I<port number> togetherseparated by a colon ( C<:> ) character or by using the  C<port> argument.To connect to a MySQL server on localhost using TCP/IP, you must specify thehostname as 127.0.0.1 (with the optional port).=item mysql_client_found_rowsEnables (TRUE value) or disables (FALSE value) the flag CLIENT_FOUND_ROWSwhile connecting to the MySQL server. This has a somewhat funny effect:Without mysql_client_found_rows, if you perform a query like  UPDATE $table SET id = 1 WHERE id = 1then the MySQL engine will always return 0, because no rows have changed.With mysql_client_found_rows however, it will return the number of rowsthat have an id 1, as some people are expecting. (At least for compatibilityto other engines.)=item mysql_compressionAs of MySQL 3.22.3, a new feature is supported: If your DSN containsthe option "mysql_compression=1", then the communication between clientand server will be compressed.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -