zoukankan      html  css  js  c++  java
  • Python的MySQLdb模块安装,连接,操作,增删改

    1. 首先确认python的版本为2.3.4以上,如果不是需要升级python的版本
         python -V   检查python版本

    2. 安装mysql, 比如安装在/usr/local/mysql目录下

    3. 下载 MySQL-python-1.2.2.tar.gz
        地址 http://sourceforge.net/projects/mysql-python/files/latest/download

    4. 安装 MySQl-python
        tar xvzf MySQL-python-1.2.2.tar.gz
        cd MySQL-python-1.2.2
        vi site.cfg
        把 mysql_config = /usr/bin/mysql/mysql_config 这一行前的#去掉,并且把mysql_config的路径设置正确。
        python setup.py build
        sudo python setup.py install
        安装结束

    5. 测试
        运行: python
        import MySQLdb
        如果没有报错,说明安装好了

    安装mysql-python错误解决方法

    _mysql.c:36:23: error: my_config.h: No such file or directory
    
    _mysql.c:38:19: error: mysql.h: No such file or directory
    
    _mysql.c:39:26: error: mysqld_error.h: No such file or directory
    
    _mysql.c:40:20: error: errmsg.h: No such file or directory
    error: command 'gcc' failed with exit status 1
    
    ----------------------------------------
    Cleaning up...
    Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_root/mysql-python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('
    ', '
    '), __file__, 'exec'))" install --record /tmp/pip-fSejm9-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_root/mysql-python
    Traceback (most recent call last):
      File "/usr/bin/pip", line 11, in <module>
        sys.exit(main())
      File "/usr/lib/python2.6/site-packages/pip/__init__.py", line 185, in main
        return command.main(cmd_args)
      File "/usr/lib/python2.6/site-packages/pip/basecommand.py", line 161, in main
        text = '
    '.join(complete_log)
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 65: ordinal not in range(128)

    解决方法:

    刚开始只看到下面的错误,以为gcc未安装的问题,后来仔细查看了安装过程,主要错误是由于找不到my_config.h文件

     yum install mysql-devel -y

    MySQLdb模块用于连接MySQL数据库。源码位于http://sourceforge.net/projects/mysql-python,其中还有用于zope的ZMySQLDA模块,通过它就可在zope中连接mysql数据库。
    
    7.1. 安装
    
    安装的方法在解压目录的README文件中有详细说明。不难,这里就不详细讲了。要注意的一点是,如果你的mysql不是安装在默认的路径,而是安装在/usr/local/mysql这样的路径的话,libmysqlclient.so.12这个动态库python可能会找不到,造成import出错,解决方法是在/usr/lib下做一个符号连接,ln -s /usr/local/mysql/lib/mysql/libmysqlclient.so.12 libmysqlclient.so.12。最后在python中用import MySQLdb测试,如果没有出错信息就说明安装成功,可以连接mysql数据库了。
    
    7.2. 模块功能
    
    connect()方法用于连接数据库,返回一个数据库连接对象。如果要连接一个位于host.remote.com服务器上名为fourm的MySQL数据库,连接串可以这样写:
    
    db = MySQLdb.connect(host="remote.com",user="user",passwd="xxx",db="fourm" )
    
    connect()的参数列表如下:
    
    host,连接的数据库服务器主机名,默认为本地主机(localhost)。
    
    user,连接数据库的用户名,默认为当前用户。
    
    passwd,连接密码,没有默认值。
    
    db,连接的数据库名,没有默认值。
    
    conv,将文字映射到Python类型的字典。默认为MySQLdb.converters.conversions
    
    cursorclass,cursor()使用的种类,默认值为MySQLdb.cursors.Cursor。
    
    compress,启用协议压缩功能。
    
    named_pipe,在windows中,与一个命名管道相连接。
    
    init_command,一旦连接建立,就为数据库服务器指定一条语句来运行。
    
    read_default_file,使用指定的MySQL配置文件。
    
    read_default_group,读取的默认组。
    
    unix_socket,在unix中,连接使用的套接字,默认使用TCP。
    
    port,指定数据库服务器的连接端口,默认是3306。
    
    连接对象的db.close()方法可关闭数据库连接,并释放相关资源。
    
    连接对象的db.cursor([cursorClass])方法返回一个指针对象,用于访问和操作数据库中的数据。
    
    连接对象的db.begin()方法用于开始一个事务,如果数据库的AUTOCOMMIT已经开启就关闭它,直到事务调用commit()和rollback()结束。
    
    连接对象的db.commit()和db.rollback()方法分别表示事务提交和回退。
    
    指针对象的cursor.close()方法关闭指针并释放相关资源。
    
    指针对象的cursor.execute(query[,parameters])方法执行数据库查询。
    
    指针对象的cursor.fetchall()可取出指针结果集中的所有行,返回的结果集一个元组(tuples)。
    
    指针对象的cursor.fetchmany([size=cursor.arraysize])从查询结果集中取出多行,我们可利用可选的参数指定取出的行数。
    
    指针对象的cursor.fetchone()从查询结果集中返回下一行。
    
    指针对象的cursor.arraysize属性指定由cursor.fetchmany()方法返回行的数目,影响fetchall()的性能,默认值为1。
    
    指针对象的cursor.rowcount属性指出上次查询或更新所发生行数。-1表示还没开始查询或没有查询到数据。
    
    7.3. 模块功能演示
    
    #!/usr/bin/python
    import MySQLdb
    try:
       connection = MySQLdb.connect(user="user",passwd="password",host="xxx",db="test")
    except:
       print "Could not connect to MySQL server."
       exit( 0 )
    try:
       cursor = connection.cursor()
       cursor.execute( "SELECT note_id,note_detail FROM note where note_id = 1" )
       print "Rows selected:", cursor.rowcount
    for row in cursor.fetchall():
           print "note : ", row[0], row[1]
       cursor.close()
    Python 连接mysql数据库
     支持SQL标准的可用数据库有很多,其中多数在Python中都有对应的客户端模块.
    
    这里我使用的mysql,它需要安装MySQLdb包.它相当于Python的数据接口规范Python DB API.
    
        
    root@10.1.1.45:~# apt-get install python-mysqldb
    root@10.1.1.45:~# python
    Python 2.5.2 (r252:60911, Jan  4 2009, 21:59:32) 
    [GCC 4.3.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import MySQLdb
    >>>
    这里导入MySQLdb没有报错,就说明安装成功.
    
    下面就可以连接数据库,可以进行增删改操作.    
    root@10.1.1.45:python# cat create.py 
    #!/usr/bin/env python
    #coding=utf-8
     
    #导入相关模块
    import MySQLdb
     
    #建立和mysql数据库的连接
    conn = MySQLdb.connect(host='localhost',user='root',passwd='davehe')
    #获取游标
    curs = conn.cursor()
    #执行SQL,创建一个数据库
    curs.execute("create database pythondb")
    #选择连接哪个数据库
    conn.select_db('pythondb')
    #执行SQL,创建一个表
    curs.execute("create table test(id int,message varchar(50))")
    #插入一条记录
    value = [1,"davehe"]
    curs.execute("insert into test values(%s,%s)",value)
    #插入多条记录
    values = []
    for i in range(20):
        values.append((i,'hello mysqldb' + str(i)))
    curs.executemany("insert into test values(%s,%s)",values)
    #提交修改                               
    conn.commit()
    #关闭游标连接,释放资源
    curs.close()
    #关闭连接
    conn.close()
    root@10.1.1.45:python# ./create.py
    下面利用python查看mysql里刚添加的记录.    
    root@10.1.1.45:python# cat select.py 
    #!/usr/bin/env python
    #coding=utf-8
     
    #导入相关模块
    import MySQLdb
     
    #建立和mysql数据库的连接
    conn = MySQLdb.connect(host='localhost',user='root',passwd='hc1226')
    #获取游标
    curs = conn.cursor()
    #选择连接哪个数据库
    conn.select_db('pythondb')
    #查看共有多少条记录
    count = curs.execute('select * from test')
    print "一共有%s条记录" % count
    #获取一条记录,以一个元组返回
    result = curs.fetchone()
    print "当前的一条记录 ID:%s message:%s" % result
    #获取后10条记录,由于之前执行了getchone(),所以游标已经指到第二条记录,下面也就从第二条记录开始返回
    results = curs.fetchmany(10)
    for r in results:
        print r
    #重置游标位置,0,为偏移量,mode = relative(默认)
    curs.scroll(0,mode='absolute')
    #获取所有记录
    results = curs.fetchall()
    for r in results:
        print r
     
    #提交修改
    conn.commit()
    #关闭游标连接,释放资源
    curs.close()
    #关闭连接
    conn.close()
        
    root@10.1.1.45:python# ./select.py 
    一共有21条记录
    当前的一条记录 ID:1 message:davehe
    (0L, 'hello mysqldb0')
    (1L, 'hello mysqldb1')
    (2L, 'hello mysqldb2')
    (3L, 'hello mysqldb3')
    (4L, 'hello mysqldb4')
    (5L, 'hello mysqldb5')
    (6L, 'hello mysqldb6')
    (7L, 'hello mysqldb7')
    (8L, 'hello mysqldb8')
    (9L, 'hello mysqldb9')
    (1L, 'davehe')
    (0L, 'hello mysqldb0')
    (1L, 'hello mysqldb1')
    (2L, 'hello mysqldb2')
    (3L, 'hello mysqldb3')
    (4L, 'hello mysqldb4')
    (5L, 'hello mysqldb5')
    (6L, 'hello mysqldb6')
    (7L, 'hello mysqldb7')
    (8L, 'hello mysqldb8')
    (9L, 'hello mysqldb9')
    (10L, 'hello mysqldb10')
    (11L, 'hello mysqldb11')
    (12L, 'hello mysqldb12')
    (13L, 'hello mysqldb13')
    (14L, 'hello mysqldb14')
    (15L, 'hello mysqldb15')
    (16L, 'hello mysqldb16')
    (17L, 'hello mysqldb17')
    (18L, 'hello mysqldb18')
    (19L, 'hello mysqldb19')
    
    附:
    
    connect函数的常用参数
    user         #用户名
    password   #用户密码
    host         #主机名
    database   #数据库名
    connect函数会返回连接对象,连接对象方法
    close()      #关闭连接之后,连接对象和它的游标均不可用
    commit()   #如果支持的话就提交挂起的事务,否则不做任何事
    rollback()   #回滚挂起的事务(可能不可用)
    cursor()     #返回连接的游标对象
    
    游标对象方法
    close()                          #关闭游标
    execute(oper[,params])    #执行SQL操作,可能使用参数
    executemany(oper,pseq)   #对序列中的每个参数执行SQL操作
    fetchone()                     #把查询的结果集中的下一行保存为序列,或者None
    fetchmany([size])            #获取查询结果集中的多行,默认为1
    fetchall()                       #将所有(剩余)的行作为序列的序列 
    python操作MySQL数据库
    2012-05-29 17:41 by Rollen Holt, 146068 阅读, 22 评论, 收藏, 编辑
    
    坚持每天学一点,每天积累一点点,作为自己每天的业余收获,这个文章是我在吃饭的期间写的,利用自己零散的时间学了一下python操作MYSQL,所以整理一下。
    
    我采用的是MySQLdb操作的MYSQL数据库。先来一个简单的例子吧:
    import MySQLdb
     try:
     conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)
        cur=conn.cursor()
        cur.execute('select * from user')
        cur.close()
        conn.close()
    except MySQLdb.Error,e:
         print "Mysql Error %d: %s" % (e.args[0], e.args[1])
    
      请注意修改你的数据库,主机名,用户名,密码。
    
    下面来大致演示一下插入数据,批量插入数据,更新数据的例子吧:
    import MySQLdb
     
    try:
        conn=MySQLdb.connect(host='localhost',user='root',passwd='root',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,%s)',values)
     
        cur.execute('update test set info="I am rollen" where id=3')
     
        conn.commit()
        cur.close()
        conn.close()
     
    except MySQLdb.Error,e:
         print "Mysql Error %d: %s" % (e.args[0], e.args[1])
    
      请注意一定要有conn.commit()这句来提交事务,要不然不能真正的插入数据。
    
    运行之后我的MySQL数据库的结果就不上图了。
    import MySQLdb
     
    try:
        conn=MySQLdb.connect(host='localhost',user='root',passwd='root',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:
         print "Mysql Error %d: %s" % (e.args[0], e.args[1])
    
      运行结果就不贴了,太长了。
    
    查询后中文会正确显示,但在数据库中却是乱码的。经过我从网上查找,发现用一个属性有可搞定:
    
    在Python代码 
    
    conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 中加一个属性:
     改为:
    conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8') 
    charset是要跟你数据库的编码一样,如果是数据库是gb2312 ,则写charset='gb2312'。
    
     
    
    下面贴一下常用的函数:
    
    然后,这个连接对象也提供了对事务操作的支持,标准的方法
    commit() 提交
    rollback() 回滚
    
    cursor用来执行命令的方法:
    callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
    execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
    executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
    nextset(self):移动到下一个结果集
    
    cursor用来接收返回值的方法:
    fetchall(self):接收全部的返回结果行.
    fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
    fetchone(self):返回一条结果行.
    scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.
    
    参考资料:
    
    MySQLdb‘s user guide
    package MySQLdb
    
     

    python连接mysql数据库增删改(示例代码)

    python连接mysql数据库的例子,提供创建表,删除表,数据增、删、改,批量插入操作。
    
    1,数据库配置类 MysqlDBConn.py
     
    复制代码 代码示例:
    
    #encoding=utf-8
    '''
    Created on 2012-11-12
    
    Mysql Conn连接类
    '''
    import MySQLdb
    class DBConn:
        conn = None
    
        #建立和数据库系统的连接
        def connect(self):
            self.conn = MySQLdb.connect(host="localhost",port=3306,user="house", passwd="house" ,db="house",charset="utf8")
    
        #获取操作游标
        def cursor(self):
            try:
                return self.conn.cursor()
            except (AttributeError, MySQLdb.OperationalError):
                self.connect()
                return self.conn.cursor()
    
        def commit(self):
            return self.conn.commit()
    
        #关闭连接
        def close(self):
            return self.conn.close()
    
    2,MysqlDemo.py类
     
    复制代码 代码示例:
    
    #encoding=utf-8
    '''
    Created on 2012-11-12
    
    @author: Steven
    
    3,Mysql操作Demo
     
    复制代码 代码示例:
    
    Done:创建表,删除表,数据增、删、改,批量插入
    '''
    import MysqlDBConn
    
    dbconn = MysqlDBConn.DBConn()
    
    def process():
        #建立连接
        dbconn.connect()
        #删除表
        dropTable()
        #创建表
        createTable()
        #批量插入数据
        insertDatas()
        #单条插入
        insertData()
        #更新数据
        updateData()
        #删除数据
        deleteData()
        #查询数据
        queryData()
        #释放连接
        dbconn.close()
    
    def insertDatas():
        sql = "insert into lifeba_users(name, realname, age) values(%s, %s, %s)"
        tmp = (('steven1', '测试1',26), ('steven2', '测试2',25))
        executemany(sql, tmp)
    
    def updateData():
        sql = "update lifeba_users set realname = '%s' where name ='steven1'"%("测试1修改")
        execute(sql)
    
    def deleteData():
        sql = "delete from lifeba_users where id=2"
        execute(sql)
    
    def queryData():
        sql = "select * from lifeba_users"
        rows = query(sql)
        printResult(rows)
    
    def insertData():
        sql = "insert into lifeba_users(name, realname, age) values('%s', '%s', %s)"%("steven3","测试3","26")
        print sql
        execute(sql)
    
    def executemany(sql, tmp):
        '''插入多条数据'''
        conn=dbconn.cursor()
        conn.executemany(sql, tmp)
    
    def execute(sql):
        '''执行sql'''
        conn=dbconn.cursor()
        conn.execute(sql)
    
    def query(sql):
        '''查询sql'''
        conn=dbconn.cursor()
        conn.execute(sql)
        rows = conn.fetchmany(10)
        return rows
    
    def createTable():
        '''创建表'''
        conn=dbconn.cursor()
        conn.execute('''
        CREATE TABLE `lifeba_users` (
          `ID` int(11) NOT NULL auto_increment,
          `name` varchar(50) default NULL,
          `realName` varchar(50) default NULL,
          `age` int(11) default NULL,
          PRIMARY KEY  (`ID`)
        ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
        ''')
    #    dbconn.commit()
    
    def dropTable():
        '''删除表'''
        conn=dbconn.cursor()
        conn.execute('''
        DROP TABLE IF EXISTS `lifeba_users`
        ''')
    #    dbconn.commit()
    
    def printResult(rows):
        for row in rows:
            for i in range(0,len(row)):#遍历数组
                print row[i], #加, 不换行打印
            print ''
    
    if __name__ == '__main__':
        process()
    
    以上分享了python连接mysql数据库,实现创建表,删除表,数据增、删、改,批量插入操作的代码,希望对大家有所帮助。
  • 相关阅读:
    iOS 字体
    接口继承和实现继承的区别
    实验楼实验——LINUX基础入门
    试看看能不能发布
    mysql binlog恢复
    percona
    ssh2 php扩展
    sphinx
    ngios
    socketlog
  • 原文地址:https://www.cnblogs.com/timssd/p/4703613.html
Copyright © 2011-2022 走看看