我目前正在尝试实现一个 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/