python mysql s_Python-MySQL

###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()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值