python操作MySQL数据库具体方法
复制代码 代码如下: import MySQLdb 请注意修改你的数据库,主机名,用户名,密码。 下面来大致演示一下插入数据,批量插入数据,更新数据的例子吧: 复制代码 代码如下: import MySQLdb try: conn=MySQLdb.connect(host='localhost',port=3306) cur=conn.cursor() cur.execute('create database if not exists python') conn.select_db('python') cur.execute('create table test(id int,info varchar(20))') value=[1,'hi rollen'] cur.execute('insert into test values(%s,%s)',value) values=[] for i in range(20): values.append((i,'hi rollen'+str(i))) cur.executemany('insert into test values(%s,values) cur.execute('update test set info="I am rollen" where id=3') conn.commit() cur.close() conn.close() except MySQLdb.Error,e.args[1]) 请注意一定要有conn.commit()这句来提交事务,要不然不能真正的插入数据。 运行之后我的MySQL数据库的结果就不上图了。 复制代码 代码如下: import MySQLdb try: conn=MySQLdb.connect(host='localhost',port=3306) cur=conn.cursor() conn.select_db('python') count=cur.execute('select * from test') print 'there has %s rows record' % count result=cur.fetchone() print result print 'ID: %s info %s' % result results=cur.fetchmany(5) for r in results: print r print '=='*10 cur.scroll(0,mode='absolute') results=cur.fetchall() for r in results: print r[1] conn.commit() cur.close() conn.close() except MySQLdb.Error,e.args[1]) 运行结果就不贴了,太长了。 查询后中文会正确显示,但在数据库中却是乱码的。经过我从网上查找,发现用一个属性有可搞定: 在Python代码 conn = MySQLdb.Connect(host='localhost',db='python') 中加一个属性: 下面贴一下常用的函数: 然后,这个连接对象也提供了对事务操作的支持,标准的方法 cursor用来执行命令的方法: cursor用来接收返回值的方法: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |