什么是Perl DBI的Python等价物?

前端之家收集整理的这篇文章主要介绍了什么是Perl DBI的Python等价物?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
什么是 Python相当于Perl的DBI以及如何使用它?更具体地说,Python等效于以下Perl代码是什么?
  1. use DBI;
  2.  
  3. # connect to a MysqL database
  4. my $dbh = DBI->connect("dbi:MysqL:database=$database; host=localhost; port=3306",$user,$pass);
  5.  
  6. # select and read a few rows
  7. my $sth = $dbh->prepare("SELECT id,name FROM table WHERE id <= ?;");
  8. $sth->execute(321);
  9. while (my @row = $sth->fetchrow_array) {
  10. my $id = $row[0];
  11. my $name = $row[1];
  12. print "$id. $name\n";
  13. }
  14.  
  15. # write to the database
  16. $sth = $dbh->prepare("INSERT INTO table (id,name) VALUES (?,?);");
  17. $sth->execute(123,"foo");

解决方法

  1. import MysqLdb.cursors
  2.  
  3. db = MysqLdb.connect(db=database,host=localhost,port=3306,user=user,passwd=pass,cursorclass=MysqLdb.cursors.DictCursor)
  4. cur = db.cursor()
  5.  
  6. #this is not string interpolation,everything is quoted for you automatically
  7. cur.execute("select id,name from table where id = %s",(321,))
  8.  
  9. for row in cur.fetchall():
  10. print "%s. %s" % (row['id'],row['name'])
  11.  
  12. cur.execute("insert into table (id,name) values (%s,%s)",(123,'foo'))
  13. db.commit() # required,because autocommit is off by default

Python数据库API使用常见的convention,在不同的数据库中几乎相同(但不完全!).您可以阅读MysqLdb文档here.

还有一个功能更丰富的MysqL接口,称为oursql.它具有真正的参数化(不仅仅是美化字符串插值),服务器端游标,数据流等.

猜你在找的Perl相关文章