码迷,mamicode.com
首页 > 数据库 > 详细

python数据库连接

时间:2019-12-15 18:37:34      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:数据库   pre   pytho   class   cut   result   local   values   tab   

连接数据库前,请先确认以下事项:

已经创建了数据库 ,表及用户名,密码

已经安装了 Python MySQLdb 模块。

数据库连接:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset=utf8 )
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
sql = """CREATE TABLE EMPLOYEE (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20),
         AGE INT,  
         SEX CHAR(1),
         INCOME FLOAT )"""
cursor.execute(sql)
db.close()

 

创建数据库表:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset=utf8 )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print "Database version : %s " % data
db.close()

数据插入:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset=utf8 )
cursor = db.cursor()
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
         LAST_NAME, AGE, SEX, INCOME)
         VALUES (‘Mac‘, ‘Mohan‘, 20, ‘M‘, 2000)"""
try:
   cursor.execute(sql)
   db.commit()
except:
db.close()

数据查询:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset=utf8 )
cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE        WHERE INCOME > %s" % (1000)
try:
   cursor.execute(sql)
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
      print "fname=%s,lname=%s,age=%s,sex=%s,income=%s" %              (fname, lname, age, sex, income )
except:
   print "Error: unable to fecth data"
db.close()

数据更新:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset=utf8 )
cursor = db.cursor()
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = ‘%c‘" % (M)
try:
   cursor.execute(sql)
   db.commit()
except:
   db.rollback()
db.close()

数据删除:

import MySQLdb
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset=utf8 )
cursor = db.cursor()
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
   cursor.execute(sql)
   db.commit()
except:
   db.rollback()
db.close()

python数据库连接

标签:数据库   pre   pytho   class   cut   result   local   values   tab   

原文地址:https://www.cnblogs.com/huanghuangwei/p/12044602.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!