Traceback (most recent call last):
File "G:\Python\myCode\Links Database\addfromtext.py", line 30, in ?
cursor.execute ("""
File "C:\Python24\Lib\site-packages\MySQLdb\cursors.py", line 129, in execute
self.errorhandler(self, ProgrammingError, m.args[0])
File "C:\Python24\Lib\site-packages\MySQLdb\connections.py", line 33, in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: not enough arguments for format string
>>>
# Script to add links from a comma deliminated file to a MySQL database
# 9/16/05
import MySQLdb
conn=MySQLdb.connect( host="www.freesql.org",
user="edhotchkiss",
port=3306,
passwd="test1",
db="links")
cursor = conn.cursor()
stmt = "DROP TABLE IF EXISTS links"
cursor.execute(stmt)
stmt = """CREATE TABLE links (
ID INT NOT NULL auto_increment,
Name TEXT,
URL LONGTEXT,
Category LONGTEXT,
primary key (ID)
)"""
cursor.execute(stmt)
inp = open ("sites.txt","r")
for line in inp.readlines():
#links = map(str, line.split(",")) # values are already strings
links = line.split(",",2) # limit to two splits
i.e. only use first 2 commas
cursor.execute ("""
INSERT INTO links (Name, URL, category)
VALUES (%s, %s, %s)""", links
)
cursor.close()
conn.close()
You should avoid sending the connection info to the list. Google will
be making this widely available. Pranksters *will* delete your tables.
Change your password!
Including the error info would help, but chances the following changes
will fix things:
stmt = """CREATE TABLE links (
ID INT NOT NULL auto_increment,
^^^^^^^^^^^^^^
Name TEXT,
URL LONGTEXT,
Category LONGTEXT,
primary key (ID)
)"""
for line in inp.readlines():
#links = map(str, line.split(",")) # values are already strings
links = line.split(",",2) # limit to two splits i.e. only use first 2 commas
arr.append(links) # arr is not used ???
cursor.execute ("""
INSERT INTO links (Name, URL, category)
VALUES (%s, %s, %s)""", links
)
You are not supplying an ID value. I assume that you want MySQL to fill
it in for you. So you need to make ID an auto_increment field.
The cursor.execute is now getting *two* arguments, the sql and the
values for the insert. Do not interpolate your values into the SQL
string. Leave that to the MySQLdb module. The %s in the VALUES serves
as a placeholder for the module and should not be used by you with the
Python string format (%) operator. This should work so long as the name
and URL never contain commas.
--
Lloyd Kvam
Venix Corp
--
edward hotchkiss
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor