python操作MySQL的详细步骤

  

描述

MySQLdb是一个Python DB api - 2.0兼容的接口;有关详细信息,请参阅pep - 249。MySQLdb的最新版本,使用主页链接。

支持版本:

* MySQL版本从3.23到5.5;5.0或更新的建议。MariaDB也应该工作。
Python版本2.4 * -2.7;Python 3支持即将到来。

ZMySQLDA Zope2数据库适配器。



<强>

[root@localhost  IdcCheck] #, wget  http://downloads.sourceforge.net/project/mysql-python/mysql-python-test/1.2.4b4/MySQL-python-1.2.4b4.tar.gz?r=https%3A%2F%2Fsourceforge.net%2Fprojects%2Fmysql-python%2F& t=1478767096, use_mirror=jaist 。   [root@localhost  IdcCheck] #, tar  -zxvf  MySQL-python-1.2.4b4.tar.gz

,,,,解压缩

[root@localhost  IdcCheck] #, tar  -zxvf  MySQL-python-1.2.4b4.tar。广州

执行   [root@localhost  IdcCheck] #, cd  MySQL-python-1.2.4b4 ,编译

[root@localhost  MySQL-python-1.2.4b4] #, python  setup.py ,构建 ,安装

[root@localhost  MySQL-python-1.2.4b4] #, python  setup.py ,安装

[root@localhost  IdcCheck] #, python   Python  2.6.6  (r266:84292, Sep  12, 2011年,14:03:14),   [GCC  4.4.5  20110214, (Red  Hat  4.4.5-6)],提醒linux2   想Type “帮助”,,“copyright",,“credits",趁机“license" for  more 信息。   在祝辞祝辞import  MySQLdb   在在在,   祝辞祝辞祝辞

import  MySQLdb      #,打开数据库连接   时间=db  MySQLdb.connect(主机=發ocalhost"用户=皉oot", passwd=皊a", db=癿ytable")      #,使用光标()方法获取操作游标,   cursor =, db.cursor ()

需要分别的关闭指针对象和连接对象

cursor.close (),   conn.close ()

<强>  python操作MySQL的详细步骤

需要注意的点:

,,1 Python文件设置编码utf - 8(文件前面加上#编码=utf - 8)

,,2 MySQL数据库utf - 8字符集=

,,Python 3连接MySQL是加上参数charset=utf8

,,4设置Python的默认编码为utf - 8 (sys.setdefaultencoding (utf - 8)


#=utf - 8编码   import 系统   import  MySQLdb      重载(系统)   sys.setdefaultencoding (& # 39; utf - 8 # 39;)      db=MySQLdb.connect(用户=& # 39;根# 39;,charset=& # 39; use utf8 # 39;) 注:

=cursor.execute监狱(sql, param)
我们要使用连接对象获得一个光标对象,接下来,我们会使用光标提供的方法来进行工作。

这些方法包括两大类:1。执行命令,2。接收返回值



,



<强>
sql=安迦隿dinfo值(% s, % s % s, % s, % s)“
<强>
参数=(标题、歌手imgurl、url、α)
<强>
n=cursor.execute (sql, param)

cursor.execute (“select * from cdinfo")

cd=cursor.fetchall ()
<强>
打印cds [0] [3]

打印cd
<强>
sql=安迦隿dinfo值(0 % s % s, % s, % s, % s)“
<强>
参数=((标题、歌手imgurl、url、α),(title2、singer2 imgurl2, url2, alpha2))
<强>
n=cursor.executemany (sql, param)
<强>

<强>


# !/usr/bin/pythonimport  MySQLdb   反对=,MySQLdb.connect(主机=& # 39;localhost # 39;,用户=& # 39;根# 39;,passwd=& # 39;根# 39;,db=& # 39; abc # 39;)   cursor =con.cursor ()   sql =皊elect  *,得到myt"   cursor.execute (sql)   行=cursor.fetchone ()   print 行   cursor.close ()   con.close ()

执行以下SQL语句获取返回值:

//获取连接的游标   光标=conn.cursor ()//查询   时间=sql “select  *,得到【表格】“//新增   时间=sql “insert  into 【表格】(字段,字段),值(值,值)“;//修改   时间=sql “update 【表格】,set 字段,=爸怠眞here 条件,“//删除   时间=sql “delete 得到【表格】where 条件,   null   null   null   null   null   null   null   null   null   null

python操作MySQL的详细步骤