Python连接MySql数据库
连接数据库
1.安装pymsql:
复制代码
1pip install pymysql
2.建立数据库连接文件dbBase.py,编辑文件内容:
复制代码
1
2
3
4
5import pymysql class DBConnect: def db_connect(DATABASE_URL): conn = pymysql.connect(host=host, port=port, user=user, passwd=password, db=db, charset=charset) cursor = conn.cursor()
3.执行SQL查询:
复制代码
1
2
3# create table sql = "create table if not exists mobile(name varchar(128) primary key, moblie_id varchar(128), moblie_name varchar(128), moblie_price varchar(128))" cursor.execute(sql)
复制代码
1
2
3
4
5
6
7# Insert one record sql = "insert into user(name, password) values ('%s', %s)" % ("张三", "bb") try: cursor.execute(sql) conn.commit() except Exception as e: print(e)
复制代码
1
2
3
4
5
6
7
8# Insert a number of records sql = "insert into user(name, moblie_id) values (%s, %s)" val = (("李四", "cc"), ("王五", "dd"), ("洪六", "ee")) try: cursor.executemany(sql, val) conn.commit() except Exception as e: print(e)
复制代码
1
2
3
4
5
6
7# Database query sql = "select * from mobile" try: cursor.execute(sql) conn.commit() except Exception as e: print(e)
复制代码
1
2
3
4
5
6
7# Database delete sql = "delete from "tablename" where "columnname" OPERATOR "value" [and|or "column" OPERATOR "value"]" try: cursor.execute(sql) conn.commit() except Exception as e: print(e)
复制代码
1
2
3
4
5
6
7# Database update sql = "update t_test t set t.password = '***' where t.bs = 2" try: cursor.execute(sql) conn.commit() except Exception as e: print(e)
指定读取数据库结果的数据类型:
MySql数据库默认的读取结果是一个元祖,有时候操作元祖并不符合业务需求,这个时候需要指定一下输出的数据类型,
方法有2种:
第一种【在连接数据库语句中设置数据库游标数据类型】
复制代码
1
2
3复制代码第二种【在获取游标的时候指定数据库游标的数据类型】conn = pymysql.connect(host=host, port=port, user=user, passwd=password, db=dbname, charset=charset, cursorclass=pymysql.cursors.DictCursor)
复制代码
1
复制代码
1cursor = conn.cursor(pymysql.cursors.DictCursor)
最后
以上就是伶俐银耳汤最近收集整理的关于Python连接MySql数据库Python连接MySql数据库的全部内容,更多相关Python连接MySql数据库Python连接MySql数据库内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复