简体   繁体   中英

Python database creation - MySQL error

I have been trying to create a database in python using the MySQL module. Here's the code:

import MySQLdb
conn = MySQLdb.connect(host = '127.0.0.1', user='root', passwd='', db='test', port='3306')
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
row = cursor.fetchone()
print "server version:",row[0]
cursor.close()
conn.close()

I had errors in initial steps relating to the host name, which I changed from localhost to the local IP and added a port keyword which seems to work with the quotes only. Apart from this, I am encountering the following error:

Traceback (most recent call last):
  File "C:\Python27\server_version", line 4, in <module>
    conn = MySQLdb.connect(host = '127.0.0.1', user='root', passwd='', db='bhavin', port='3306')
  File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
TypeError: an integer is required

port should be an integer, not a string:

conn = MySQLdb.connect(host='127.0.0.1', 
                       user='root', 
                       passwd='', 
                       db='test', 
                       port=3306)

Though, note that 3306 is a default port used if not provided explicitly:

port

TCP port of MySQL server. Default: standard port (3306).

Any way you are not creating a db table with that code, you are going to get an error, like "No such table exists" or something like that. Your should try: CREATE TABLE IF NOT EXISTS(" // columns of your table with the type like integer or varchar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM