Python/pymysql: Difference between revisions
< Python
No edit summary |
No edit summary |
||
Line 2: | Line 2: | ||
* [[Mysql/CheatSheet]] | * [[Mysql/CheatSheet]] | ||
* [[Mysql]] | * [[Mysql]] | ||
== Examples == | |||
* connect | |||
<pre> | |||
import pymysql | |||
db = pymysql.connect(host=localhost, port=3306, user="root", password="1234") | |||
</pre> | |||
* show version | |||
<pre> | |||
try: | |||
with db: | |||
cursor = db.cursor() | |||
cursor.execute("SELECT VERSION()") | |||
version = cursor.fetchone() | |||
print("Database version: {}".format(version[0])) | |||
except Exception as e: | |||
print(e) | |||
</pre> | |||
* create database | |||
<pre> | |||
try: | |||
with db: | |||
cursor = db.cursor() | |||
cursor.execute("CREATE DATABASE carsearch") | |||
except Exception as e: | |||
print(e) | |||
</pre> |
Revision as of 16:55, 15 June 2020
Examples
- connect
import pymysql db = pymysql.connect(host=localhost, port=3306, user="root", password="1234")
- show version
try: with db: cursor = db.cursor() cursor.execute("SELECT VERSION()") version = cursor.fetchone() print("Database version: {}".format(version[0])) except Exception as e: print(e)
- create database
try: with db: cursor = db.cursor() cursor.execute("CREATE DATABASE carsearch") except Exception as e: print(e)