在mysql中插入数据

时间:2014-11-16 13:31:05

标签: python mysql twitter tweepy

你是我的新手python并且还在学习我想要从twitter重新插入一些数据到db这里是我的代码

    import MySQLdb
    import tweepy
    from tweepy import OAuthHandler
    CONSUMER_KEY = 'A'
    CONSUMER_SECRET = 'A'
    ACCESS_KEY = 'A'
    ACCESS_SECRET = 'A'
    auth = OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
    api = tweepy.API(auth)
    auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
    user = api.get_user(2883100465)
    print user.id
    print user.screen_name
    print user.name
    print user.profile_image_url
    print user.location
    print user.url
    print user.description
    print user.created_at
    print user.followers_count
    print user.friends_count
    print user.statuses_count
    print user.time_zone
    # Open database connection
    db = MySQLdb.connect("localhost","root","root","EgoNetwork");
    # prepare a cursor object using cursor() method
    cursor = db.cursor()
    # Prepare SQL query to INSERT a record into the database.
    sql = "INSERT INTO profile(user_id,screen_name,name,profile_image_url,location,url,description,created_at,followers_count,friends_count,statuses_count,time_zone,last_update) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)";
    try:
    cur.execute(sql,("2829756343",user.screen_name,user.name,user.profile_image_url,user.location,user.url,user.description,user.created_at,user.followers_count,user.friends_count,user.statuses_count,user.time_zone,""))
       db.commit()
    except:
       # Rollback in case there is any error
       db.rollback()

    # disconnect from server
    db.close()

这是我的错误代码

File "UserProfile.py", line 31
cur.execute(sql,("2829756343",user.screen_name,user.name,user.profile_image_url,user.location,user.url,user.description,user.created_at,user.followers_count,user.friends_count,user.statuses_count,user.time_zone,""))
  ^

IndentationError:预期缩进块

1 个答案:

答案 0 :(得分:1)

你需要在try下缩进cur.execute。而不是

try:
cur.execute(sql,("2829756343",user.screen_name,user.name,user.profile_image_url,user.location,user.url,user.description,user.created_at,user.followers_count,user.friends_count,user.statuses_count,user.time_zone,""))
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

这样做:

try:
    cur.execute(sql,("2829756343",user.screen_name,user.name,user.profile_image_url,user.location,user.url,user.description,user.created_at,user.followers_count,user.friends_count,user.statuses_count,user.time_zone,""))
    db.commit()
except:
    # Rollback in case there is any error
    db.rollback()

请注意,错误消息说“IndentationError:期望缩进块”