Python2 连接数据库
# -*- coding: utf-8 -*-
import os
import MySQLdb
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# conn=MySQLdb.connect(host="127.0.0.1",port=22066,user="root",passwd="123456",db="dsideal_db",charset="utf8")
conn=MySQLdb.connect(
host='101.200.43.145',
user='root',
passwd='c87CF67Sstudio1q',
db='c27studio',
port=3306,
charset='utf8'
)
cursor = conn.cursor()
# 删除数据库
#cursor.execute("drop table student")
#创建数据表
cursor.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
# 查询
sql = "select * from c_user"
n = cursor.execute(sql)
for row in cursor.fetchall():
print row
#插入一条数据
cursor.execute("insert into student values('2','Tom','3 year 2 class','9')")
#修改查询条件的数据
#cursor.execute("update student set class='3 year 1 class' where name = 'Tom'")
#删除查询条件的数据
#cursor.execute("delete from student where age='9'")
conn.commit()
conn.close()
Python3 连接数据库
__author__ = 'xxx'
import pymysql
try:
conn=pymysql.connect(
host='65.49.204.74',
user='test',
passwd='test',
db='test',
port=3306,
charset='utf8'
)
cur=conn.cursor()
cur.execute('select * from student')
data=cur.fetchall()
for d in data :
print (d)
cur.close()
conn.close()
except Exception :print("发生异常")