Python MySQL 更新表
UPDATE 对任何数据库的操作都会更新数据库中已有的一条或多条记录。你可以使用 UPDATE 语句更新 MySQL 中现有记录的值。要更新特定行,你需要同时使用 WHERE 子句。
语法
MySQL中UPDATE语句的语法如下:
UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition];
你可以使用 AND 或 OR 运算符组合 N 个条件。
例子
假设我们在 MySQL 中创建了一个名为 EMPLOYEES 的表:
mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); Query OK, 0 rows affected (0.36 sec)
如果我们使用 INSERT 语句向其中插入了 4 条记录:
mysql> INSERT INTO EMPLOYEE VALUES ('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'F', 5000), ('Mac', 'Mohan', 26, 'M', 2000);
以下 MySQL 语句将所有男性员工的年龄增加一岁:
mysql> UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M'; Query OK, 3 rows affected (0.06 sec) Rows matched: 3 Changed: 3 Warnings: 0
如果检索表的内容,可以看到更新后的值如下:
mysql> select * from EMPLOYEE; +------------+-----------+------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | +------------+-----------+------+------+--------+ | Krishna | Sharma | 20 | M | 2000 | | Raj | Kandukuri | 21 | M | 7000 | | Ramya | Ramapriya | 25 | F | 5000 | | Mac | Mohan | 27 | M | 2000 | +------------+-----------+------+------+--------+ 4 rows in set (0.00 sec)
使用 Python 更新表的内容
在 MySQL 中使用 python 更新表中的记录:
-
import mysql.connector package.
-
使用 mysql.connector.connect() 方法,通过将用户名、密码、主机(可选默认值:localhost)和数据库(可选)作为参数传递给它。
-
通过调用 cursor() 上面创建的连接对象上的方法。
-
然后,通过将 UPDATE 语句作为参数传递给 执行() method.
例子
以下示例将所有男性的年龄增加一岁。
import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Preparing the query to update the records sql = '''UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M' ''' try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database conn.commit() except: # Rollback in case there is any error conn.rollback() #Retrieving data sql = '''SELECT * from EMPLOYEE''' #Executing the query cursor.execute(sql) #Displaying the result print(cursor.fetchall()) #Closing the connection conn.close()
[('Krishna', 'Sharma', 22, 'M', 2000.0), ('Raj', 'Kandukuri', 23, 'M', 7000.0), ('Ramya', 'Ramapriya', 26, 'F', 5000.0) ]