Get the App
SLTechnology News&Howtos  ›  Database  › 

Python3 connects to Mysql database

Shulou Source: shulou.com Published: 2022-06-01 12:17:26 09月27日 Update

Beginners to learn Python, whether it is e-books or online tutorials, are aimed at python2.7, but there are changes in some grammar and modules.

such as

Urllib2 is a module that comes with python and does not need to be downloaded.

Urllib2 is changed to urllib.request in python3.x

The most common way to connect to MySQL in Python 2.x is MySQLdb. This module is also used in a large number of tutorials online (I have never been successful in installing it through pip install MySQLdb).

Currently, MySQLdb does not support python3.x. You can use MySQL connnecter instead.

Import mysql.connectorimport sysuser = 'root'pwd =' root'host = '20.0.2.50'db='mysql'create_tab_sql = "CREATE TABLE IF NOT EXISTS TAB_TEST (\ TAB_NAME VARCHAR (20),\ CITY_NAME VARCHAR (20))\ CHARACTER SET utf8" conn = mysql.connector.connect (user=user,password=pwd,host=host) Database=db) cursor = conn.cursor () try: cursor.execute (create_tab_sql) except mysql.connector.Error as err: print ("create table 'tab_test' failed.") Print ("Error: {}" .format (err.msg)) sys.exit ()

Tags: Modules tutorials success that is commonly used e-books grammar or parts changes support data databases Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Technology Shulou Information MySQL Huawei