如何从SQL数据库导入数据?

时间:2018-09-17 06:32:59

标签: python mysql python-3.x pycharm

我将本地数据库连接到应用程序,然后我想将这些数据再次带入应用程序进行编辑。那是我的代码

import sys
import os
import time

from PyQt5 import QtCore, QtGui, QtWidgets, uic
import mysql.connector
from mysql.connector import errorcode

FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__),"mahmoudtarek.ui"))

class Main(QtWidgets.QMainWindow, FORM_CLASS):
    def __init__(self,parent=None):
        super(Main,self).__init__(parent)
        self.setupUi(self)
        self.InitUI()
        self.conn = None

        self.handle_buttons()
        self.handle_db_connections()

    def InitUI(self):
        ## changes in the run time
        pass

    def handle_buttons(self):
          ## all buttons in the app
        self.pushButton.clicked.connect(self.add_mahmoud_friends)
        self.pushButton_3.clicked.connect(self.update_mahmoud_friends)
        self.pushButton_2.clicked.connect(self.delete_mahmoud_friends)
        self.pushButton_6.clicked.connect(self.search_mahmoud_friends)


    def handle_db_connections(self):
        try:
            self.conn = mysql.connector.connect(
                host='127.0.0.1',
                database='mydb',
                user='root',
                password='134668691011',
                use_pure=True)  # use_pure is set to true

            if self.conn.is_connected():
                db_Info = self.conn.get_server_info()
                print("Connected to MySQL database using C extension... MySQL Server version on ", db_Info)
        except mysql.connector.Error as err:
            print("Error while connecting to MySQL using C extension", err)

    def add_mahmoud_friends(self):
        mth_friends = self.lineEdit.text()
        mth_search = self.lineEdit_4.text()
        if self.conn:
            c = self.conn.cursor()
            try:
                c.execute('''INSERT INTO ahmed (mth_friends,mth_search) values (%s,%s)''', (mth_friends,mth_search))
                self.conn.commit()
                self.lineEdit.setText('')
                self.lineEdit_4.setText('')
                self.statusBar.showMessage('ok mahmoud')


            except mysql.connector.Error as err:
                print("Error: ", err)

    def update_mahmoud_friends(self):
        pass

    def delete_mahmoud_friends(self):
        pass
    def search_mahmoud_friends(self):

        sql = '''SELECT * FROM ahmed WHERE mth_search = %s'''
        mth_search = self.lineEdit_3.text()
        self.conn.cursor.execute(sql , [(mth_search)])
        data = self.conn.fetchall()
        for row in data :
            print(row)

    def closeEvent(self, event):
        if self.conn:
            self.conn.close()
        super(Main, self).closeEvent(event)


def main():
    app= QtWidgets.QApplication(sys.argv)
    window =Main()
    window.show()
    app.exec_()

if __name__ == '__main__':
    main()

当我通过在SQL数据库中打印行来导入数据时,这里会出现错误。

错误

  

使用C扩展名连接到MySQL数据库... MySQL服务器版本   在8.0.12上进行追溯(最近一次通话为最后一次):文件   “ /Users/mahmoudtarek/Desktop/mth1/index.py”,第73行,在   search_mahmoud_friends       self.conn.cursor.execute(sql,[[mth_search)])AttributeError:“函数”对象没有属性“执行”

     

那么,它可以解决还是有另一种方法?

3 个答案:

答案 0 :(得分:2)

尝试将第73行更改为

self.conn.cursor().execute(sql , [(mth_search)])

答案 1 :(得分:0)

也许您可以尝试以下类似操作

import pymssql
cnxn = pymssql.connect(server='Server_name',user='UID', password='Password', database='Db Name')
cursor = cnxn.cursor()    
cmd = (r"<Your Query>")
cursor.execute(cmd)
query_results = cursor.fetchall()
cursor.close()

结果将显示在query_results

答案 2 :(得分:0)

  

我解决了,谢谢大家

  def search_mahmoud_friends(self):
        if self.conn:
            c = self.conn.cursor()

            try:

                sql = '''SELECT * FROM ahmed WHERE mth_search = %s'''
                mth_search = self.lineEdit_3.text()
                c.execute(sql, [(mth_search)])
                data = c.fetchall()
                for row in data :
                    print(row)

            except mysql.connector.Error as err:
              print("Error: ", err)