0

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

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

8 Comments

that gives me 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='test', 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) OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (10061)")
@user3451879 and this is a different problem.
its taking 10061 as default port
@user3451879 nope, 10061 is not a port here.
@user3451879 first of all, make sure your credentials are correct and MySQL server is up and running.
|
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.