Get the App
SLTechnology News&Howtos  ›  Database  › 

Simple operation of adding, deleting, modifying and querying Python3 database

Shulou Source: shulou.com Published: 2022-06-01 04:53:22 09月29日 Update

1, add a table using Python

# Import the module used to operate the database

Import pymysql

# establishing a connection database object

Conn=pymysql.connect (host='127.2.2.2',user='root',passwd='123456',db='records')

# create a cursor

Cur=conn.cursor ()

# execute the sql statement with the method in the cursor

Cur.execute ("create table people (name char (20), height int (3), weight int (3)")

# close the cursor after the statement is executed

Cur.close ()

# close the connection to the database

Conn.close ()

The above code can be viewed in the database after execution, and a table of people has been created.

2, insert a piece of data in the table.

# execute the sql statement with the method in the cursor

Cur.execute ("insert into people values ('tom',110,34)")

# submit the insert operation you just did to make it effective

Conn.commit ()

3. Modify a piece of data in the table to change height to 177,

# execute the sql statement with the method in the cursor

Cur.execute ("update people set height=177 where name='tom'")

# submit the insert operation you just did to make it effective

Conn.commit ()

4, query the data in the table

# execute the sql statement with the method in the cursor

Cur.execute ("select * from people")

The # fetchall method can capture the result of the statement executed by select above.

Print (cur.fetchall ())

5. Delete the data in the table

# execute the sql statement with the method in the cursor

Cur.execute ("delete from people where name='tom'")

# submit the insert operation you just did to make it effective

Conn.commit ()

Tags: Data cursors statements methods databases code objects query tables modules results queries Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Apple OPPO Reno Shulou Technology MySQL