python - 数据未插入到 mySQL (MariaDB) 表中

标签 python mysql database raspberry-pi mariadb

我目前正在尝试实现一个 python 脚本,它将在我的 SQL 数据库 (MariaDB) 的表中插入几个虚拟值。我在 Raspberry Pi 上使用 Stretch OS。

我首先在 MariaDB 的现有数据库中成功创建了一个表。

MariaDB [testdb]> CREATE table testdbtable (col1 char(1), col2 char(1), col3 char(1));
Query OK, 0 rows affected (0.12 sec)

使用showtables;我可以看到testdbtable作为我创建的表。

+------------------+
| Tables_in_testdb |
+------------------+
| testdbtable      |
+------------------+
1 row in set (0.00 sec)

使用show columns from testdbtable;我得到:

+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| col1  | char(1) | YES  |     | NULL    |       |
| col2  | char(1) | YES  |     | NULL    |       |
| col3  | char(1) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

然后我创建了一个 python 脚本:

#!/usr/bin/python
import mysql.connector as mariadb 

mariadb_connection = mariadb.connect(user='root', password='', database='testdb')

cursor = mariadb_connection.cursor()

cursor.execute("INSERT INTO testdbtable(col1, col2, col3) VALUES ('a', 'b', 'c')");

mariadb_connection.close()

该脚本在终端上运行没有任何错误。但是,当我在终端上运行 MariaDB 时,我没有看到虚拟值(即 a、b、c)从我的脚本插入到此表中:

MariaDB [testdb]> select * from testdbtable;
Empty set (0.00 sec)

如果有人可以就我的脚本中可能做错的地方提供任何建议,我将不胜感激?

最佳答案

我想您需要提交更改。参见这篇文章

https://mariadb.com/resources/blog/how-connect-python-programs-mariadb

cursor.execute("INSERT INTO testdbtable(col1, col2, col3) VALUES ('a', 'b', 'c')");

mariadb_connection.commit()

关于python - 数据未插入到 mySQL (MariaDB) 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47927910/

相关文章:

Python diff 两个列表的时间复杂度是多少?

mysql - 随时间变化的 Oracle Select

database - <java.lang.ClassNotFoundException : com. microsoft.sqlserver.jdbc.SQLServerDriver> 通过窗口调度程序在后台连接 SQL 时

python - 在 python 中以格式化字符串列出打印

python - 如何使用 fields_get 方法编辑 View ?

python - Matplotlib 图形未在 GitHub CodeSpaces 中生成

mysql - 在 MySQL 中检索上周的所有日期

mysql - 在 c 脚本中连接到 mysql?

MySQL 根据结果选择

mysql - 如果另一个查询编辑了这些结果,数据库如何维护这些结果