Python连接Mysql数据库

第一步:安装
安装Python,到官网https://www.360docs.net/doc/7810712248.html,上下载
安装MySQL,到官网https://www.360docs.net/doc/7810712248.html,上下载
安装MySQL-python-1.2.2.win32-py2.6.exe,到https://www.360docs.net/doc/7810712248.html,/archives/4上下载

第二步:使用
创建数据库,创建表,插入数据,插入多条数据

Python代码:
#!/usr/bin/env python
#coding=utf-8

import MySQLdb

#建立和数据库系统的连接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')

#获取操作游标
cursor = conn.cursor()
#执行SQL,创建一个数据库.
cursor.execute("""create database if not exists python""")

#选择数据库
conn.select_db('python');
#执行SQL,创建一个数据表.
cursor.execute("""create table test(id int, info varchar(100)) """)

value = [1,"inserted ?"];

#插入一条记录
cursor.execute("insert into test values(%s,%s)",value);

values=[]


#生成插入参数值
for i in range(20):
values.append((i,'Hello mysqldb, I am recoder ' + str(i)))
#插入多条记录

cursor.executemany("""insert into test values(%s,%s) """,values);

#关闭连接,释放资源
cursor.close();

################################################################################
#插入多条记录:

#!/usr/bin/env python
#coding=utf-8

import MySQLdb

#建立和数据库系统的连接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')

#获取操作游标
cursor = conn.cursor()
#执行SQL,创建一个数据库.
cursor.execute("""create database if not exists python""")

#选择数据库
conn.select_db('python');
#执行SQL,创建一个数据表.
cursor.execute("""create table test(id int, info varchar(100)) """)

value = [1,"inserted ?"];

#插入一条记录
cursor.execute("insert into test values(%s,%s)",value);

values=[]

#生成插入参数值
for i in range(20):
values.append((i,'Hello mysqldb, I am recoder ' + str(i)))
#插入多条记录

cursor.executemany("""insert into test values(%s,%s) """,values);

#关闭连接,释放资源
cursor.close();
查询和插入的流程差不多,只是多了一个得到查询结果的步骤

#####################################################################################
#查询

#!/usr/bin/env python
#coding=utf-8

import MySQLdb

conn = MySQLdb.connect(host='localhost', user='root', passwd='longforfreedom',db='python')

cursor = conn.cursor()

count = cursor.execute('select * from test')

print '总共有 %s 条记录',count

#获取一条记录,每条记录做为一个元组返回
print "只获取一条记录:"
result = cursor.fetchone();
print result
#print 'ID: %s info: %s' % (result[0],result[1])
print 'ID: %s info: %s' % result

#获取5条记录,注意由

于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的所有记录
print "只获取5条记录:"
results = cursor.fetchmany(5)
for r in results:
print r

print "获取所有结果:"
#重置游标位置,0,为偏移量,mode=absolute | relative,默认为relative,
cursor.scroll(0,mode='absolute')
#获取所有结果
results = cursor.fetchall()
for r in results:
print r
conn.close()




第三步:一些异常和错误
1.python 插入数据不成功 (mysql)

代码如下:
#!/usr/bin/env python
import socket,MySQLdb,sys,random,time
conn=MySQLdb.connect('127.0.0.1','root','1','asterisk')
cursor=conn.cursor()
cursor.execute('insert into test(a) values(1)')
print "a"
cursor.close()
conn.close()

运行 后没有 报错, 但表没有 插入记录, , insert into test(a) values(1) 这句sql 在 mysql 下运行是成功的

解决办法:
是事务忘了提交,在close上面加一行
https://www.360docs.net/doc/7810712248.html,mit()提交修改
一般情况下,MySQLdb模块会自动提交修改。但我们在更新数据后,手动运行一次:
https://www.360docs.net/doc/7810712248.html,mit()


2.无法定位程序输入点 mysql_server_init 于动态链接库 LIBMYSQL.dll 上
Python 版本:2.5
----------------------------------------------------------------------------------------------------
D:\usr\local\Python25>python
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
File "", line 1, in
File "D:\usr\local\Python25\Lib\site-packages\MySQLdb\__init__.py", line 19, in
import _mysql
ImportError: DLL load failed: 找不到指定的程序。
----------------------------------------------------------------------------------------------------
解决方法:把mysql安装目录的bin\libmySQL.dll文件复制到python安装目录的Lib\site-packages下


3.ImportError: DLL load failed: 找不到指定的模块。
Python 版本:2.6
----------------------------------------------------------------------------------------------------
D:\usr\local\Python26>python
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
File "", line 1, in
File "D:\usr\local\Python26\Lib\site-packages\MySQLdb\__init__.py", line 19, in

import _mysql
ImportError: DLL load failed: 找不到指定的模块。
----------------------------------------------------------------------------------------------------
解决方法:下载libmmd.dll和libguide40.dll两个dll文件并复制System32目录或者D:\usr\local\Python26\Lib\site-packages之下


4.ImportError: DLL load failed: 找

不到指定的模块。
----------------------------------------------------------------------------------------------------
D:\usr\local\Python26>python
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
D:\usr\local\Python26\lib\site-packages\MySQLdb\__init__.py:34: DeprecationWarning: the sets module is deprecated
from sets import ImmutableSet
----------------------------------------------------------------------------------------------------
解决方法:
1) 在文件中 "__init__", 注释掉:
from sets import ImmutableSet
class DBAPISet(ImmutableSet):
新增:
class DBAPISet(frozenset)

2) 在文件中"converters.py", 注释掉 from sets import BaseSet, Set 这一句话。

3) 在文件中"converters.py", 修改 "Set" 成为 "set" ( 只有两个地方需要修改):
大概 line 48: return Set([ i for i in s.split(',') if i ]) 》》 return set([ i for i in s.split(',') if i ])
大概 line 128: Set: Set2Str, 》》 set: Set2Str

相关主题
相关文档
最新文档