Chinaunix首页 | 论坛 | 博客
  • 博客访问: 629014
  • 博文数量: 87
  • 博客积分: 3399
  • 博客等级: 中校
  • 技术积分: 1422
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-17 21:20
文章分类

全部博文(87)

文章存档

2013年(1)

2012年(51)

2011年(33)

2010年(2)

分类: Python/Ruby

2012-04-22 17:14:41

     parseExceltoDB.pl

实现的功能为:

         1)创建数据库stucourse,包括三个表:student,course,grade.

2)将stucourse.xls的内容导入到数据库stucourse中,将数据分别导入到三个表中。

3)从数据库中读取数据,统计选课人数超过10的课程名称及各个学生的平均成绩。


 

点击(此处)折叠或打开

  1. ####################################################################################################
  2. #file : parseExceltoDB.pl
  3. #author : Yusheng Jia
  4. #date : 4.22.2012
  5. #version: 1.0
  6. #desc : this script will create a database,
  7. # parse the spreadsheet and export the data into the database,
  8. # and do some analyses based on the data.
  9. ###################################################################################################

  10. ##------------------------------------------------------------------------------------------------
  11. ##利用perl DBI创建数据库stucourse,并创建student,course,grade表
  12. ##------------------------------------------------------------------------------------------------
  13. use DBI;
  14. my $db_name = "stucourse"; #数据库名,如果与现有数据库冲突,可改为其他名字
  15. my $db_host = "localhost"; #主机名
  16. my $db_port = '3306'; #端口号
  17. my $username = "root"; #用户名
  18. my $password = "leo"; #密码
  19. my $dsn = "dbi:mysql:database=${db_name};hostname=${db_host};port=${db_port}";#数据源

  20. #获取驱动程序对象句柄
  21. my $drh=DBI->install_driver("mysql");
  22. #如果存在数据库$db_name,则删除之
  23. if($rc = $drh->func("dropdb",$db_name ,$db_host,$username,$password,"admin") ){
  24.     print "drop database `",$db_name,"` successfully!\n";
  25. }
  26. #创建数据库$db_name
  27. $rc = $drh->func("createdb",$db_name ,$db_host,$username,$password,"admin")or
  28.     die "failed to create database ",$db_name,"!\n";
  29. print "create database `stucourse` successfully!\n";

  30. #获取数据库句柄
  31. my $dbh = DBI -> connect ($dsn, $username, $password,{RaiseError => 1, PrintError => 0})or
  32.     die "failed to connect to the database!\n",DBI->errstr();

  33. #设置数据库字符集,防止中文乱码
  34. my $charset = "set character_set_database=utf8";
  35. my $sth = $dbh->prepare($charset);
  36. $sth->execute();

  37. #创建表course
  38. my $query = "CREATE TABLE `course` ( "
  39.             ."`cid` int(10) NOT NULL auto_increment,"
  40.             ."`cno` varchar(20) NOT NULL, "
  41.             ."`cname` varchar(20) default NULL, "
  42.             ."PRIMARY KEY (`cid`)"
  43.             .")ENGINE=InnoDB DEFAULT CHARSET=utf8;";
  44. my $sth = $dbh->prepare($query);
  45. $sth->execute() or die "create table course error: ".$sth->errstr();
  46. print "create table `course` successfully!\n";

  47. #创建表student
  48. my $query = "CREATE TABLE `student` ("
  49.             ."`sid` int(10) NOT NULL auto_increment,"
  50.             ."`sno` varchar(20) NOT NULL,"
  51.             ."`sname` varchar(20) default NULL,"
  52.             ."PRIMARY KEY (`sid`)"
  53.             .")ENGINE=InnoDB DEFAULT CHARSET=utf8;";
  54. my $sth = $dbh->prepare($query);
  55. $sth->execute() or die "create table student error: ".$sth->errstr();
  56. print "create table `student` successfully!\n";

  57. #创建表grade
  58. my $query = "CREATE TABLE `grade` ("
  59.          ."`gid` int(10) NOT NULL,"
  60.          ."`cid` int(10) NOT NULL,"
  61.          ."`sid` int(10) NOT NULL,"
  62.          ."`grade` int(10) default NULL,"
  63.          ."PRIMARY KEY (`gid`),"
  64.          ."KEY `cid` (`cid`),"
  65.          ."KEY `sid` (`sid`),"
  66.          ."CONSTRAINT `cid` FOREIGN KEY (`cid`) REFERENCES `course`(`cid`),"
  67.          ."CONSTRAINT `sid` FOREIGN KEY (`sid`) REFERENCES `student`(`sid`)"
  68.          .") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
  69. my $sth = $dbh->prepare($query);
  70. $sth->execute() or die "create table grade error: ".$sth->errstr();
  71. print "create table `grade` successfully!\n";

  72. #关闭数据库连接
  73. $dbh->disconnect();

  74. ##------------------------------------------------------------------------------------------------
  75. ##利用Spreadsheet::ParseExcel解析Excel文件,并将其数据导入数据库stucourse.
  76. ##------------------------------------------------------------------------------------------------
  77. use strict;
  78. use Spreadsheet::ParseExcel;
  79. use Spreadsheet::ParseExcel::FmtUnicode; #字符编码

  80. my $xlsFile = "stucourse.xls"; #Excel数据源文件,由于使用的ParseExcel,只支持97-2003,
  81.                                            #请使用xls格式的数据源文件
  82. my $head = 1; #如果sheet有表头则为1,否则设置为0
  83. my $dbh = DBI -> connect ($dsn, $username, $password,{RaiseError => 1, PrintError => 0});
  84. unless($dbh){
  85.     print "Error opening database: $DBI::errstr \n";
  86.     exit;
  87. }
  88. #设置连接字符集
  89. my $charset = "set character_set_connection=utf8";
  90. my $sth = $dbh->prepare($charset);
  91. $sth->execute();

  92. my $parser = Spreadsheet::ParseExcel->new();
  93. my $formatter = Spreadsheet::ParseExcel::FmtUnicode->new(Unicode_Map=>"CP936");#设置字符编码
  94. my $workbook = $parser->parse($xlsFile, $formatter);#按所设置的字符编码解析
  95. if ( !defined $workbook ) {
  96.     die $parser->error(), ".\n";
  97. }

  98. print "\nThere are ".$workbook->{SheetCount}." sheets in $xlsFile.\n";

  99. my $stuSheet = $workbook->{Worksheet}[0];
  100. my $couSheet = $workbook->{Worksheet}[1];
  101. my $graSheet = $workbook->{Worksheet}[2];

  102. #将student表中的数据插入到数据库,一次查询语句,插入多条记录
  103. $query = "insert into `student`(sid,sno,sname) values";
  104. my ( $row_min, $row_max ) = $stuSheet->row_range();
  105. my ( $col_min, $col_max ) = $stuSheet->col_range();

  106. for my $row ( $row_min+$head .. $row_max ) {
  107.     $query .="(".$stuSheet->get_cell($row,0)->value().",'"
  108.     .$stuSheet->get_cell($row,1)->value()."','"
  109.     .$stuSheet->get_cell($row,2)->value()."'),"
  110. }
  111. $query = substr($query,0,length($query)-1).";";
  112. #print $query;
  113. my $rv = $dbh->do($query)or die "insert failed!";
  114. print "import ".$stuSheet->{Name}." successfully!\n";

  115. #将course表中的数据插入到数据库,一次查询语句,插入多条记录
  116. $query = "insert into `course`(cid,cno,cname) values";
  117. my ( $row_min, $row_max ) = $couSheet->row_range();
  118. my ( $col_min, $col_max ) = $couSheet->col_range();

  119. for my $row ( $row_min+$head .. $row_max ) {
  120.     $query .="(".$couSheet->get_cell($row,0)->value().",'"
  121.     .$couSheet->get_cell($row,1)->value()."','"
  122.     .$couSheet->get_cell($row,2)->value()."'),"
  123. }
  124. $query = substr($query,0,length($query)-1).";";
  125. my $rv = $dbh->do($query)or die "insert failed!";
  126. print "import ".$couSheet->{Name}." successfully!\n";

  127. #将grade表中的数据插入到数据库,一次查询语句,插入多条记录
  128. $query = "insert into `grade`(gid,cid,sid,grade) values";
  129. my ( $row_min, $row_max ) = $graSheet->row_range();
  130. my ( $col_min, $col_max ) = $graSheet->col_range();

  131. for my $row ( $row_min+$head .. $row_max ) {
  132.     $query .="(".$graSheet->get_cell($row,0)->value().","
  133.     .$graSheet->get_cell($row,1)->value().","
  134.     .$graSheet->get_cell($row,2)->value().","
  135.     .$graSheet->get_cell($row,3)->value()."),"
  136. }
  137. $query = substr($query,0,length($query)-1).";";
  138. my $rv = $dbh->do($query)or die "insert failed!";
  139. print "import ".$graSheet->{Name}." successfully!\n";

  140. ##------------------------------------------------------------------------------------------------
  141. ##利用perl读取数据库中的内容,对其中的数据进行分析
  142. ##------------------------------------------------------------------------------------------------

  143. #查询统计选课人数超过10的课程
  144. $query = "select cid, cname"
  145.         ." from course"
  146.         ." where cid in("
  147.         ." select cid"
  148.         ." from grade"
  149.         ." group by cid"
  150.         ." having count(cid)>10"
  151.         .");";
  152. $sth = $dbh->prepare($query);
  153. $sth->execute() or die "query error!\n";
  154. print "\nThe courses that be token by at least 10 students are:\n";
  155. while(my @result=$sth->fetchrow_array){
  156.     print "$result[0] $result[1] \n";
  157. }
  158. $sth->finish();

  159. #查询各个学生的平均成绩
  160. $query = "select s.sid, s.sname,avg(grade)"
  161.         ." from student s, grade g"
  162.         ." where s.sid=g.sid"
  163.         ." group by g.sid;";
  164. $sth = $dbh->prepare($query);
  165. $sth->execute() or die "query error!\n";
  166. print "\nThe average grade of every student:\n";
  167. while(my @result=$sth->fetchrow_array){
  168.     print "$result[0] $result[1] $result[2]\n";
  169. }
  170. $sth->finish();
  171. #关闭数据库连接
  172. $dbh->disconnect();
  173. ###################################################################################################


 

阅读(3511) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~