python连接mysql并进行操作代码

#python连接mysql代码


conn = MySQLdb.Connect(
	host = "192.168.146.128",
	port = 3306,
	user = "root",
	passwd = "123456",
	db = "imooc",
	charset = "utf-8")

curosr = conn.cursor()
print conn
print cursor
cursor.close()
conn.close()


#select查询数据库


import MySQLdb

conn = MySQLdb.Connect(
	host = "192.168.146.128",
	port = 3306,
	user = "root",
	passwd = "123456",
	db = "imooc",
	charset = "utf-8")

curosr = conn.cursor()
sql = "select * from user"
try:
	cursor.execute(sql)
	print cursor.rowcount
	rs = cursor.fetchone()
	print rs	
	rs = cursor.fetcmany(3)
	print rs
	rs = cursor.fetcall()
	print rs
except Exception as e:
	print e
	conn.rollback()
cursor.close()
conn.close()


#insert/update/delete操作


import MySQLdb
conn = MySQLdb.Connect(
	host = "192.168.146.128",
	port = 3306,
	user = "root",
	passwd = "123456",
	db = "imooc",
	charset = "utf-8")

curosr = conn.cursor()

sql_insert = "insert into user(userid, username) values(10, 'name10')"
sql_update = "update user set username = 'name91' where userid = 9"
sql_delete = "delete from user where userid < 3"
try:
	cursor.execute(sql_insert)
	print cursor.rowcount
	cursor.execute(sql_update)
	print cursor.rowcount
	cursor.execute(sql_delete)
	print cursor.rowcount
except Exception as e:
	print e
	conn.rollback()

cursor.close()
conn.close()


你可能感兴趣的:(Database,Python)