0

I am coding with mysql-python.

To add a new record into database, I use the following piece of code:

# Open database connection
db = MySQLdb.connect("localhost","root","admin","majoranalysis" )
# prepare a cursor object using cursor() method 
cursor = db.cursor()    
sql = "INSERT INTO 
# insert a record
jobdetail(title,date_accessed,description,requirement,url) \
    VALUES(%(title)s,%(data_accessed)s,%(description)s,%(requirement)s,%(url)s)"
dt =  ('data analysist',date(2015,4,16),'description','requirement',joblistlink[0])
cursor.execute(sql,dt)

The problem is not to declare str, but the error occurs likely:

Traceback (most recent call last):
File "./re-ex.py", line 81, in <module>
dt =  ('data analysist',date(2015,4,16),'description','requirement',joblistlink[0])
TypeError: 'str' object is not callable

The sql command to create the table is:

CREATE TABLE IF NOT EXISTS `jobdetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
`date_accessed` date NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
`requirement` text COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

Do you know where is the bug?

1
  • 1
    If you use values like this for mysql%(description) should dt be a dictionarly? Commented Apr 16, 2015 at 3:01

1 Answer 1

1

Because you use the %(key)s as a place holder in your sql str.So that means you should use a dictionary to give the data to the sql.

Eg.

give tuple to %s like :print "%s:%s" % ('key', 'val')

give dict to %(key)s like print '%(k1)s:%(v1)s' % {'k1':'key', 'v1':'val'}

In case you still dont know how to fix your problem.Change to

dt={'title':'data analysist',
    'data_accessed':date(2015,4,16),
    'description':'description',
    'requirement':'requirement',
    'url':joblistlink[0]}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks anyway @amow. But it has not still worked for me, although changing dt to the same to you.
@Tung I review your code and err msg.I think your problem is happened before the cursor.execute.Maybe there is a code mistake before the dt declare.Why your sql string declare with multiple lines but use the "?Is this your origin code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.