yl197837 发表于 2018-9-28 13:36:35

Python 原生模块 操作Mysql

1.操作mysql代码;  

  
# -*- coding: utf-8 -*-
  
import MySQLdb
  
def get_conn():
  
    host = "192.168.xxx.xx"
  
    port = 3306
  
    db = "Scier"
  
    user = "root"
  
    password = "123456"
  
    conn = MySQLdb.connect(host, user, password, db, port, charset='utf8')
  
    return conn
  

  
class User(object):
  

  
    def save(self,type, name, url, create_time, create_founder):
  
            self.type = type
  
            self.name = name
  
            self.url = url
  
            self.create_time = create_time
  
            self.create_founder = create_founder
  
            conn = get_conn()
  
            cursor = conn.cursor()
  
            sql = ("insert into naming (type,name,url,create_time,create_founder) VALUES (%s,%s,%s,%s,%s)")
  
            data = (self.type, self.name, self.url, self.create_time, self.create_founder)
  
            try:
  
                cursor.execute(sql, data)
  
                conn.commit()
  
                cursor.close()
  
                conn.close()
  
            except:
  
                cursor.close()
  
                conn.close()
  
                return "Error: unable to table naming"
  

  
    def Query_naming(self,type1):
  
         conn = get_conn()
  
         cursor = conn.cursor()
  
         self.type1 = type1
  
         # SQL 查询语句命名规范名称和url地址字段#######
  
         sql = "SELECT NAME,url FROM naming WHERE TYPE='%s'" % self.type1
  
         try:
  
               # 执行SQL语句
  
               cursor.execute(sql)
  
               # 获取所有记录列表
  
               results = cursor.fetchall()
  
               cursor.close()
  
               conn.close()
  
               returnresults
  
         except:
  
               cursor.close()
  
               conn.close()
  
               return "Error: unable to fecth data"
  
name = User()
  
abc = name.Query_naming('发布规范类')
  
abc = name.Query_naming('环境治理类')


页: [1]
查看完整版本: Python 原生模块 操作Mysql