This question already has an answer here:

I created python script with one function that connect to mysql db, retrieves non spatial data, creates features and saves them into new layer. Below is the pseuodo code:

def create_features (mysql_connection)
    layer = QgsVectorLayer(xxx)
    provider = layer.dataProvider()
    fields = provider.fields()
    features = []

    mysql_connection.cursor.execute("select * from tables")

    for res1,res2,re3 in mysql_connection.cursor.fetchall():
    #store results to a layer attributes

    _writer = QgsVectorFileWriter.writeAsVectorFormat(layer, path_to_shape_file)

#import mysql_select
myConnection = MySQLdb.connect(db_credentials)

It works fine. But I want to divide all stuff to modules located in different .py files to get more comfortable development. I modified the code above to mysql_select.py and my_main_script.py according to the marks ### above. But I get the error "NameError: global name 'QgsVectorLayer' is not defined".

What is the problem? How to send layer variable to the external module? What is the best method to divide the code into different modules in this case? I have to make four sql selects and create 4 new layers, so to put all that stuff in one script seems not versatile to develop.

I`ve tried to put from qgis.core import QgsVectorLayer in the mysql_select.py and in the my_main_script.py but unsuccessful.

marked as duplicate by Matthias Kuhn, mgri, Mapperz Mar 30 '17 at 16:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Browse other questions tagged or ask your own question.