On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. connections on Unix to localhost are made using a Unix socket file by default The Cursor object enables you to run the execute() method, which in turn enables you to run raw SQL statements (in this case, a SELECT query on a table named employee).The classic answer to this issue is to use 127.0.0.1 or the IP of the host or the host name instead of the "special name" localhost. When you have a Connection object associated with a database, you can create a Cursor object. Because all three MySQL modules use the portable SQL database API interface, they are able to use the code in the doQuery() function without any modifications. This example creates a series of Connection objects that opens the same database using different MySQL modules. M圜onnection = nnect( host=hostname, user=username, passwd=password, db=database ) M圜onnection = ( host=hostname, user=username, passwd=password, db=database ) # Simple routine to run a query on a database and print the results:Ĭur.execute( "SELECT fname, lname FROM employee" )įor firstname, lastname in cur.fetchall() : In your own code, replace username with the MySQL database username, password with the database user's password, and dbname with the database name: #!/usr/bin/python The sample code works with Python 2.7 and Python 3.x. The following sample Python code demonstrates how to do this, as well as just how easy it is to switch between the different SQL package implementations. To install the pymysql package, type the following command:Īfter you install a MySQL package in the virtual environment, you are ready to work with actual databases. To install the mysql-connector-python package, type the following command:
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |