怎么用python导入SQL

Python014

怎么用python导入SQL,第1张

访问MYSQL的话使用,MySQLdb模块

import os,sys

import MySQLdb

try:

conn=MySQLdb.connect(host='localhost',user='root',passwd="",db='YOURDB')

except Exception,e:

print e

sys.exit()

cursor=conn.cursor()

sql="insert into address(name,address) values (%s,%s)"

values=(("zhang","being"),("li","beijing"),("wang","beijing"))

try:

cursor.executemany(sql,values)#插入数条数据

except Exception , e:

print e

sql="select * from address"

cursor.execute(sql) #查询

data=cursor.fetchall()

if data:

for x in data:

print x[0],x[1]

cursor.close()#关闭游标

conn.close()#关闭数据库

第一种办法

# 导入SQLite驱动:

>>> import sqlite3

# 连接到SQLite数据库

# 数据库文件是test.db

# 如果文件不存在,会自动在当前目录创建:

>>> conn = sqlite3.connect('test.db')

# 创建一个Cursor:

>>> cursor = conn.cursor()

# 执行一条SQL语句,创建user表:

>>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')

<sqlite3.Cursor object at 0x10f8aa260>

# 继续执行一条SQL语句,插入一条记录:

>>> cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')

<sqlite3.Cursor object at 0x10f8aa260>

# 通过rowcount获得插入的行数:

>>> cursor.rowcount

1

# 关闭Cursor:

>>> cursor.close()

# 提交事务:

>>> conn.commit()

# 关闭Connection:

>>> conn.close()

第二种办法:

使用 SQLalchemy 等ORM 的库。