How do I connect to a MySQL Database in Python?

后端 未结 25 1584
眼角桃花
眼角桃花 2020-11-21 07:43

How do I connect to a MySQL database using a python program?

25条回答
  •  臣服心动
    2020-11-21 08:07

    mysqlclient is the best as others only provide support to specific versions of python

     pip install mysqlclient
    

    example code

        import mysql.connector
        import _mysql
        db=_mysql.connect("127.0.0.1","root","umer","sys")
        #db=_mysql.connect(host,user,password,db)
        # Example of how to insert new values:
        db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")
        db.store_result()
        db.query("SELECT * FROM new1.table1 ;") 
        #new1 is scheme table1 is table mysql 
        res= db.store_result()
        for i in range(res.num_rows()):
            print(result.fetch_row())
    

    see https://github.com/PyMySQL/mysqlclient-python

提交回复
热议问题