Python连接Mysql数据库遇到的一系列问题

本人用的是python3,如果要连接Mysql,你大概首先要安装MySQL驱动:

$ pip install mysql-connector-python --allow-external mysql-connector-python

由于MySQL服务器以独立的进程运行,并通过网络对外服务,所以,需要支持PythonMySQL驱动来连接到MySQL服务器。MySQL官方提供了mysql-connector-python驱动,但是安装的时候需要给pip命令加上参数--allow-external

连接数据库是一件很简单的事情。不过我找了半天,也没有找到Mysqlpython api的介绍,不过最后还是到Mysql的官网翻到了。我直接当下来给大家一个参考:
http://download.csdn.net/detail/lishuhuakai/9310301

下面记录一下我遇到的一些问题,以及解决方案。

1. Not all parameters were used in the SQL statement

下面看一看我的例子:

def insert_into_bk(book_list, cursor):
    """
    这个函数主要用于将表单里面的数据存入book表单
    :param book_list:
    :return:
    """
    '''
    add_book = ("INSERT INTO books "
                "(title, author_info, pub_info, pub_time, price, rating, book_tag) "
                "VALUES (\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', %f, \'%s\')")
    '''
    add_book = ("INSERT INTO books "
                "(title, author_info, pub_info, pub_time, price, rating, book_tag) "
                "VALUES (%s, %s, %s, %s, %s, %f, %s)")

    for each_book in book_list:
        print(each_book)
        try:
            cursor.execute(add_book, each_book)
        except mysql.connector.Error as err:
            print(err.msg)


def add_items_into_db(book_list):
    # 连接到数据库
    db = mysql.connector.connect(host='169.254.138.77',user='dbuser1', password='123',
                             database='test', port='3306')
    cursor = db.cursor()

    insert_into_bk(book_list, cursor)
    db.commit()
    db.close()
if __name__ == '__main__':
    book_list = [('依葫芦','sdf','sdfa','sdfa', 20, 16.1,'sdf')]

    # sql = add_book % ('sdf','sdf','sdfa','sdfa','sdf', 16.1,'sdf')
    # print(sql)
    add_items_into_db(book_list)

你或许压根就找不到错误,怎么可能会出错,参数个数明明是正确的啊,怎么会报错说Not all parameters were used?

原因很简单,在这里VALUES (%s, %s, %s, %s, %s, %f, %s),将f改为s–>VALUES (%s, %s, %s, %s, %s, %s, %s),立马好了。
下面是老外的一段解释。

Note that the parameter markers used by mysql.connector may look the same as the %s used in Python string formatting but the relationship is only coincidental. Some database adapters like oursql and sqlite3 use ? as the parameter marker instead of %s.

2.Incorrect string value

这个问题在于字符集问题,我的建议是在建表的时候就设定表的字符集,如我下面的表单。

def create_bk_tb(db, cursor):
    """
    用来创建book表单
    :param db:
    :return:
    """
    tb = {}
    tb['books'] = (
    "CREATE TABLE `books` ("
    "  `title` varchar(50) NOT NULL,"
    "  `author_info` varchar(150),"
    "  `pub_info` varchar(50),"
    "  `pub_time` varchar(16),"
    "  `price` varchar(20),"
    "  `rating` float,"
    "  `book_tag` varchar(50),"
    "  PRIMARY KEY (`title`)"
    ") ENGINE=InnoDB CHARSET=utf8")


    try:
        print("正在创建book表...")
        cursor.execute(tb['books'])
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
            print("already exists.")
        else:
            print(err.msg)
    print("OK")

在建表的同时设定了字符集为utf-8,这样最方便,其余的解决方案请看其他人的博客。

3. python如何向mysql插入特殊字符

如果自己来处理的话,很困难,因为你无法判断一个字段中是否有应该转义的字符。

insert into table book(title, author, pub) values ('green'body', 'li', 'china');

上面的语句是会出错的,因为green'body的单引号没有转义,自己如果手工去转义的话会非常麻烦,还好,Mysql考虑到了这一点。

cursor.execute()可以接受一个参数,也可以接受两个参数:
第一种方式是直接给一个sql语句:

 sql = 'insert into table book(title, author, pub) values (\'green\'body\', \'li\', \'china\');' # 记得要转义
 cursor.execute(sql) # 很麻烦对吧

第二种方式就很优雅啦,让execute来替我们转义:

sql = 'insert into table book(title, author, pub) values (%s, %s, %s)';
cursor.execute(sql, ('green\'body', 'li', 'china'))

推荐使用第二种方式。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值