用perl如何訪問mysql數據庫?請給個例子

熱心網友

mysql create database mydata; Query OK, 1 row affected (0。00 sec) mysql use mydata; Database changed mysql create table address ( - id int(5) not null, - name varchar(40) not null, - email varchar(50) not null, - telephone int(12) null); Query OK, 0 rows affected (0。05 sec)mysql insert into address values ( - 1,’Nighthawk’,’nighthawk@ ’, ); Query OK, 1 row affected (0。00 sec) use DBI; #連接數據庫mydata my $dbh = DBI-connect(’DBI:mysql:mydata’) or die "無法連接數據庫: " 。 DBI-errstr; print "插入若干記錄n"; my $sth = $dbh-prepare(q{ INSERT INTO address (id, name,email,telephone) VALUES (?, ?, ?, ?) }) }); print "輸入記錄,回車結束:"; while ($inputdata =) { chop $inputdata; last unless($inputdata); my ($id, $name,$email, $tel) = split( /,/, $inputdata); $sth-execute($id, $name, $email,$tel) } # $dbh-commit; print "下面根據輸入的名字打印出EMAIL地址和電話n"; my $sth = $dbh-prepare(’SELECT * FROM address WHERE name=?’) or die $dbh-errstr; print "請輸入姓名,回車結束:"; while ($inputname =) { my @data; chomp $inputname; last unless($inputname); $sth-execute($inputname) or die "錯誤: " 。 $sth-errstr; while (@data = $sth-fetchrow_array()) { print "Email:$data[2]t Telephone:$data[3]n"; } } #斷開連接 $dbh-disconnect; 。