ModuleNotFoundError:没有名为“ MySQLdb”的模块

时间:2018-10-27 18:11:07

标签: python flask mysql-python

完成我的一个Flask项目后,我像其他人一样将其上传到github。在2-3个月的时间后,我将整个githube存储库下载到另一台计算机上以运行它。但是,该应用程序无法正常工作,因为找不到提供以下消息的软件包

  

ModuleNotFoundError:没有名为“ Flask”的模块

所以我最终下载了Flask,SQLalchemy等所有软件包!但我被MySQLdb困住了:

(MYAPPENV) C:\Users\hp\myapp>python run.py
Traceback (most recent call last):
  File "run.py", line 1, in <module>
    from app import app
  File "C:\Users\hp\myapp\app\__init__.py", line 4, in <module>
    from instance.config import engine
  File "C:\Users\hp\myapp\instance\config.py", line 52, in <module>
    engine = create_engine("mysql://root:root@localhost/MYAPPDB")
  File "C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\__init__.py", line 425, in create_engine
return strategy.create(*args, **kwargs)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\engine\strategies.py", line 81, in create
dbapi = dialect_cls.dbapi(**dbapi_args)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sqlalchemy\dialects\mysql\mysqldb.py", line 102, in dbapi
    return __import__('MySQLdb')
ModuleNotFoundError: No module named 'MySQLdb'

有人可以帮助解决这个问题吗?我在Windows机器上使用python37。我什至尝试下载mysqlclient,.. etc等软件包,但没有成功。

6 个答案:

答案 0 :(得分:2)

我已经阅读到python3不支持mysqldb

看起来,当您尝试连接到数据库时,默认情况下使用的是mysql db连接到数据库!

您需要通过编辑DATABASE_URI密码来更改它

但是在您需要安装连接器扩展时:

使用此命令:

pip install mysql-connector-python

根据this documentation,您可以编辑DATABSE_URI并更改默认连接器,如下所示:

DATABSE_URI='mysql+mysqlconnector://{user}:{password}@{server}/{database}'.format(user='your_user', password='password', server='localhost', database='dname')

我希望这会有所帮助。...

答案 1 :(得分:1)

要安装MySQLdb,只要您的计算机上安装了pippip3

pip install mysqlclient

答案 2 :(得分:1)

您可以使用 mysqlclient

安装 pip

尝试:

pip3 install mysqlclient

python2

中的

pip install mysqlclient

答案 3 :(得分:1)

import pymysql
pymysql.install_as_MySQLdb()

答案 4 :(得分:1)

互联网人好,

由于相同的问题,我到达此页面。
但是我正在使用Ubuntu 18.04和Python 3.6

Python代码段- app.py

from flask import Flask, render_template
from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_HOST'] = 'YourHost' 
app.config['MYSQL_USER'] = 'YourUserName'
app.config['MYSQL_PASSWORD'] = 'UserPassword'
app.config['MYSQL_DB'] = 'TheDbName'
mysql = MySQL(app)

app.secret_key = 'YourUltimateSuperSecretKey'

@app.route('/')
@app.route('/index')
def index():
    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM users')
    data = cur.fetchall()
    cur.close()
    return render_template('index.html', test = data)

if __name__ == "__main__":
    app.run(debug=True)

HTML- index.html

<div>
    {% for x in test %}
        {{ x }}
    {% endfor %}
</div>

这就是我要解决的问题:
首先,我安装了缺少的软件包:

sudo apt install python3-mysqldb

之后,我在环境上使用pip安装了这些库:

pip安装Flask-MySQLdb mysql-connector-python

并成功运行:)

答案 5 :(得分:0)

我遇到了与您相同的问题。我的解决方案是这样的,希望它可以为您提供帮助:

1。原因:python3.X不支持MySQLdb,更改为pymysql模型 2.解决方案: 更改导入内容。

1):

let commentBar = MessageInputBar()

var showsCommentBar = false
var posts = [PFObject]()
var selectedPost: PFObject!

override func viewDidLoad() {
    super.viewDidLoad()
    commentBar.inputTextView.placeholder = "Add a comment....."
    commentBar.sendButton.title = "Post"
    commentBar.delegate = self

    tableView.delegate = self
    tableView.dataSource = self
    tableView.keyboardDismissMode = .interactive //dismisses keyboard
    // Do any additional setup after loading the view.
    let center = NotificationCenter.default
    center.addObserver(self, selector: #selector(keyboardWillbeHidden(note:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWillbeHidden(note: Notification){
    commentBar.inputTextView.text = nil
    showsCommentBar = false
    becomeFirstResponder()
}

override var inputAccessoryView: UIView{
    return commentBar
}

override var canBecomeFirstResponder: Bool{
    return showsCommentBar
}


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)


    let query = PFQuery(className: "Posts")
     query.includeKeys(["author", "comments", "comments.author"])
    query.limit = 20
    query.findObjectsInBackground{ (posts, error) in
        if posts != nil{
            self.posts = posts!
            self.tableView.reloadData()
        }
    }
}

func messageInputBar(_ inputBar: MessageInputBar, didPressSendButtonWith text: String) {
    //create comment
    let comment = PFObject(className: "Comments")
    //let comment = comments[indexPath.row]
    comment["text"] = text
    comment["post"] = selectedPost
    comment["author"] = PFUser.current()!
    selectedPost.add(comment, forKey: "comments")
    selectedPost.saveInBackground{(success, error) in
        if success{
            print("comment saved!")

        }else{
             print("Error12: \(String(describing: error))")

        }


    }

    tableView.reloadData()
    //clear and dismiss bar
    commentBar.inputTextView.text = nil
    showsCommentBar = false
    becomeFirstResponder()
    commentBar.inputTextView.resignFirstResponder()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let post = posts[section]
    let comments = (post["comments"] as? [PFObject]) ?? []
    return comments.count + 2
}

func numberOfSections(in tableView: UITableView) -> Int {
    return posts.count
}



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

     let post = posts[indexPath.section]
    let comments = (post["comments"] as? [PFObject]) ?? []


    if indexPath.row == 0{
    let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell")  as! PostCell


    let user = post["author"] as! PFUser
    cell.usernameLabel.text = user.username

    cell.captionLabel.text = post["caption"] as! String


    let imageFile = post["image"] as! PFFileObject
    let urlString = imageFile.url
    let url = URL(string: urlString!)!

    cell.photoView.af_setImage(withURL: url)

    return cell
    }else if indexPath.row <= comments.count{
        let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell") as! CommentCell

        let comment = comments[indexPath.row - 1]
        cell.commentLabel.text = comment["text"] as? String
        let user = comment ["author"] as! PFUser
        cell.nameLabel.text = user.username
        return cell


    }else{
        let cell = tableView.dequeueReusableCell(withIdentifier: "AddCommentCell")!
        return cell;
    }
}
//creates new columns
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   // let post = posts[indexPath.row]
    let post = posts[indexPath.section]
    //let comment = PFObject(className: "Comments")
    let comments = (post["comments"] as? [PFObject]) ?? []
    //let comment = comments[indexPath.row]
    if indexPath.row == comments.count + 1{
        showsCommentBar = true
        becomeFirstResponder()
        commentBar.inputTextView.becomeFirstResponder()
        selectedPost = post
    }

    /*comment["text"] = "random comment1"
    comment["post"] = "post"
    comment["author"] = PFUser.current()
    post.add(comment, forKey: "comments")
    post.saveInBackground{(success, error) in
        if success{
            print("comment saved!")

        }else{
            print("error saving comments")
        }

    }
    */


    }
}

2):

replace all MySQLdb with pymysql

3)

def reconnect(self):
    """Closes the existing database connection and re-opens it."""
    self.close()
    self._db = pymysql.connect(**self._db_args)# MySQLdb.connect(**self._db_args)
    self._db.autocommit(True)

4):

if pymysql is not None:
    # Fix the access conversions to properly recognize unicode/binary
    FIELD_TYPE = pymysql.connections.FIELD_TYPE # MySQLdb.constants.FIELD_TYPE
    FLAG = pymysql.constants.FLAG# MySQLdb.constants.FLAG
    CONVERSIONS = copy.copy (pymysql.converters.conversions)# (MySQLdb.converters.conversions)

    field_types = [FIELD_TYPE.BLOB, FIELD_TYPE.STRING, FIELD_TYPE.VAR_STRING]
    if 'VARCHAR' in vars(FIELD_TYPE):
        field_types.append(FIELD_TYPE.VARCHAR)

    for field_type in field_types:
        # CONVERSIONS[field_type] = [(FLAG.BINARY, str)] + CONVERSIONS[field_type]
        CONVERSIONS[field_type] = [(FLAG.BINARY, str)].append(CONVERSIONS[field_type])

    # Alias some common MySQL exceptions
    IntegrityError = pymysql.IntegrityError# MySQLdb.IntegrityError
    OperationalError = pymysql.OperationalError# MySQLdb.OperationalError

5):

def __init__(self, host, database, user=None, password=None,
                 max_idle_time=7 * 3600, connect_timeout=10,# 设置连接超时时间,时间是秒
                 time_zone="+0:00", charset = "utf8", sql_mode="TRADITIONAL"):
相关问题