###Python 使用MySQLdb
import MySQLdb
#连接MySQL \
# connect方法用于创建数据库连接,里面可以指定参数,主机,用户,密码等。\
# 这只是连接到数据库,想对数据库进行操作,需要创建游标
conn = MySQLdb.connect(host = '192.168.1.2',
user = 'root',
passwd = '123123',
port = 3306,
db = 'test')
#创建游标
cur = conn.cursor()
#通过游标cur操作execute方法可以写入sql语句
cur.execute("create table user(id int (11), number int(11)")
#关闭游标 \
#提交事务 \
#关闭数据库连接
cur.close()
conn.commit()
conn.close()
####插入数据:
import MySQLdb
conn = MySQLdb.connect(host = '192.168.1.2',
user = 'root',
passwd = '123123',
port = 3306,
db = 'test')
cur = conn.cursor()
#一次插入多条纪录
fs = 'insert into user(%s, %s)'
cur. executemany(fs, [
('1', '123'),
('2', '456'),
('3', '789')]
)
cur.close()
conn.commit()
conn.close()
####获取MySQL数据
import MySQLdb
conn = MySQLdb.connect(host = '192.168.1.2',
user = 'root',
passwd = '123123',
port = 3306,
db = 'test')
cur = conn.cursor()
#获取表中多少条数据
fs = cur. execute('select * from user')
print fs
#打印表中多少条数据
info = cur. fetchmany(fs)
for line in info:
print i
cur.close()
conn.commit()
conn.close()