Home >Backend Development >Python Tutorial >Python connects to mysql

Python connects to mysql

高洛峰
高洛峰Original
2017-02-28 10:22:271220browse

Python connects to mysql

Without further ado, let’s go directly to the code:

#!/usr/bin/python
#coding:utf-8

import MySQLdb

#建立和mysql数据库的连接
con = MySQLdb.connect(host="127.0.0.1",port=3306,user="root",passwd="000000")

#获取游标
cursor = con.cursor()

#选择数据库
con.select_db('WY_yun')

#执行SQL,创建一个表
cursor.execute("create table mm(id int,name varchar(20))")

#插入一条记录
value = (1,"user")
cursor.execute("insert into mm values(%s,%s)",value)
#cursor.execute("insert into mm values(1,'user')")

#插入多条记录
values = [(2,"user2"),(3,"user3")]
cursor.executemany("insert into mm values(%s,%s)",values)
#cursor.execute("insert into mm values(2,'Zuser'),(3,'Wuser')")


#查询
sql = "select * from mm"
res =  cursor.execute(sql)

#获取一条记录
#info = cursor.fetchone()

#获取多跳数据
infoo = cursor.fetchmany(res)

#打印表中数据
for line in infoo:
        print line

#提交
con.commit()
#关闭游标
cursor.close()
#关闭连接
con.close()

Note:

When deleting or updating, con.commit() is required; select and insert() can succeed without commit().

For more articles related to Python connection to mysql, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn