Python_MySQL插入与查询

数据库的插入与查询

表的设计

21.JPG

以下代码包含:连接、插入、查询

import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='root',
                             password='123456',
                             db='bishetest',
                             charset='utf8',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO table1(mhname) VALUES ('4444');"  
        cursor.execute(sql)  

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT * FROM table1"
        cursor.execute(sql)  #, ('[email protected]',)
        # result = cursor.fetchone()
        result2= cursor.fetchall()  #返回数组
        # print(result2)
        for i in result2:
            print(i)
finally:
    connection.close()

查询结果

22.JPG

你可能感兴趣的:(Python_MySQL插入与查询)