Найти - Пользователи
Полная версия: Вставка строки в таблицу MySQL
Начало » Python для новичков » Вставка строки в таблицу MySQL
1
degid
Здасти, создал вот такую таблицу:
CREATE TABLE IF NOT EXISTS `test_tab` (
  `system_id` int(5) NOT NULL AUTO_INCREMENT,
  `id` int(4) NOT NULL,
  `name` char(255) DEFAULT NULL,
  `filtered_name` char(255) DEFAULT NULL,
  `real` enum('false','true') DEFAULT NULL,
  `image` char(255) DEFAULT NULL,
  PRIMARY KEY (`system_id`),
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

При добавлении строки таким макаром:

# 2.7
# -*- coding: utf-8 -*-
from mysql.connector import MySQLConnection, Error
data_in_db = {'id': '2', 'name': 'test-test-test', 'filtered_name': 'test', 'real': 'true', 'image': '/images/2.jpg'}
query = "INSERT INTO test_tab(id, name, filtered_name, real, image) " \
							"VALUES(%d, %s, %s, %s, %s)"
args = (data_in_db.get('id'), data_in_db.get('name'), data_in_db.get('filtered_name'), data_in_db.get('real'), data_in_db.get('image'))
	
db_config = {'password': 'root', 'host': 'localhost', 'user': 'root', 'database': 'anime'}	
	
try:
	conn = MySQLConnection(**db_config)
	
	cursor = conn.cursor()
	cursor.execute(query, args)
	if cursor.lastrowid:
		print('last insert id', cursor.lastrowid)
	else:
		print('last insert id not found')
	conn.commit()
			
except Error as error:
	print(error)
	
finally:
	cursor.close()
	conn.close()
выскакивает ошибка "Wrong number of arguments during string formatting"
Что я делаю не так?
Делаю по вот этому примеру: http://www.internet-technologies.ru/articles/article_2190.html
но там не указана структура таблицы
FishHook
degid
Здасти
Пливет, малышь!

"INSERT INTO test_tab(id, name, filtered_name, real, image) VALUES(%d, %s, %s, %s, %s)"
Попробуй заменить %d на %s
degid
Другая ошибка теперь - "1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘real, image) VALUES(2, ’test-test-test', ‘test’, ‘true’, ‘/images/2.jpg’)' at line 1
Видимо, есть какой-то нюанс с ”enum"….
py.user.next
real - имя колонки, а там есть тип real. Либо переназови, либо в обратные кавычки заключи.

mysql> create table test (a int, b real);
Query OK, 0 rows affected (0.06 sec)

mysql> desc test;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| a | int(11) | YES | | NULL | |
| b | double | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql>

Пример:
mysql> create table test (real int, b real);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'real int, b real)' at line 1
mysql> create table test (`real` int, b real);
Query OK, 0 rows affected (0.08 sec)

mysql> desc test;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| real | int(11) | YES | | NULL | |
| b | double | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> insert into test (real, b) values (1, 1.5);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'real, b) values (1, 1.5)' at line 1
mysql> insert into test (`real`, b) values (1, 1.5);
Query OK, 1 row affected (0.01 sec)

mysql> select * from test;
+------+------+
| real | b |
+------+------+
| 1 | 1.5 |
+------+------+
1 row in set (0.00 sec)

mysql>
degid
Спасибо, добавилось.
degid
Подскажите ещё по этой таблице! Если передаю данные с длинной = 1 символ
args = '1'
cursor.execute("""SELECT * FROM genres WHERE id=%s""", (args))
то запрос выполняется, а если длина двухзначная, то опять та же ошибка
args = '10'
cursor.execute("""SELECT * FROM genres WHERE id=%s""", (args))

Wrong number of arguments during string formatting
С чем это связано?
FishHook
degid
С чем это связано?
C тем, что вы не знаете питон.
В этом языке не скобки определяют кортеж, а запятая между элементами.
Вот это (“10”) нифига не кортеж. программа выполняет цикл по строке “10”, а в этой строке 2 элемента.
А вот это (“10”, ) - кортеж элементов с длиной 1.
degid
Заработало!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB