MySQL interface of Perl DBI: An Example

Source: Internet
Author: User
Source code:#! /Usr/bin/perl-w
# Test. pl-Perl DBI test

Use strict;
Use DBI;

My $ dsn = "DBI: mysql: db1: 10.1.9.110"; # data source name
My $ user_name = "user1"; # user name
My $ password = "passwd1"; # password

# Connect to database
My $ dbh = DBI-> connect ($ dsn, $ user_name, $ password, {RaiseError => 1, PrintError => 0 });

# Issue query
My $ something = $ dbh-> prepare ("select * from month. temp order by id asc ");
My $ sth_bal;
My $ update_bal;
My $ delete_subtasks;

$ Something-> execute ();

$ Dbh-> do ("set foreign_key_checks = 0 ");

# Read resules of query, then clean up
While (my ($ id, $ SubscriptionID, $ UserID, $ ServiceID, $ Price) = $ something-> fetchrow_array ())
{
$ Sth_bal = $ dbh-> prepare ("select c1 from db1.t1 where UserID = $ UserID ");
$ Sth_bal-> execute ();
My ($ balance) = $ sth_bal-> fetchrow_array ();

If ($ Price> $ balance)
{
$ Delete_subparts = $ dbh-> do ("delete from db1.t2 where c1 = $ SubscriptionID ");
If (! $ Delete_subtasks)
{
Print "an error occurredn ";
}
Else
{
# Print "subscriptionid: $ subscriptionid ";
# Print "N ";
}
$ DBH-> do ("insert into db2.log (optdate, opt, tablename, subscriptionid, userid, oldbal, newbal)
Values (curdate (), 'delete', 'servicesubregion', $ SubscriptionID, $ UserID, null, null )");
}
Else
{
$ Update_bal = $ dbh-> do ("update db1.t1 set UserBal = UserBal-$ Price where UserID = $ UserID ");
If (! $ Update_bal)
{
Print "An error occurredn ";
}
Else
{
# Print "userid: $ userid ";
# Print "N ";
}
$ DBH-> do ("insert into db2.log (optdate, opt, tablename, subscriptionid, userid, oldbal, newbal)
Values (curdate (), 'update', 'webuser', $ subscriptionid, $ userid, $ balance, $ balance-$ price )");
}
$ Sth_bal-> finish ();
}

$ Something-> finish ();

$ DBH-> do ("set foreign_key_checks = 1 ");

$ DBH-> disconnect ();
Exit (0 );

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.