Get the App
SLTechnology News&Howtos  ›  Database  › 

Using Python to connect and manipulate the mysql database method

Shulou Source: shulou.com Published: 2022-06-01 19:21:49 10月03日 Update

Here's how to use Python to connect to and manipulate mysql databases. The secret of the text is that it is relevant to the topic. So, no gossip, let's go straight to the following, I believe you will benefit from reading this article on using Python connections and manipulating mysql database methods.

The 1.MySQLdb module is an interface for Python to link to Mysql databases. It is not installed by default.

[root@python ~] # yum install MySQL-python-y

two。 Create a python script

[root@python ~] # cat mysql.py

#! / usr/bin/env python

#-*-coding: UTF-8-*-

Import MySQLdb as mysql # Import MySQLdb module

Db=mysql.connect (user='root',passwd='centos',db='test',host='localhost') # connect to the database

Cursor=db.cursor () # create a cursor object

Sql='create table test (id int,name varchar (8));'# create a table

Cursor.execute (sql) # execute sql statement

Db.close () # close the connection

3. Execute the script and enter the library to see if it is successful.

[root@python] # mysql-uroot-pcentos

Mysql > use test

Database changed

Mysql > show tables

+-+

| | Tables_in_test |

+-+

| | test |

+-+

1 row in set (0.00 sec)

Mysql > desc test

+-+ +

| | Field | Type | Null | Key | Default | Extra | |

+-+ +

| | id | int (11) | YES | | NULL |

| | name | varchar (8) | YES | | NULL |

+-+ +

2 rows in set (0.00 sec)

Is there anything you don't understand about the above methods of using Python to connect and manipulate mysql databases? Or if you want to know more about it, you can continue to follow our industry information section.

Tags: Data databases methods modules scripts success the following topics content places mysteries objects interfaces text more plates cursors articles industries statements Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Microsoft Huawei Xiaomi Redmi