Python/pymysql: Difference between revisions
< Python
(Die Seite wurde neu angelegt: „-> Mysql“) |
|||
(10 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
- | {| class="wikitable" style="float:right; margin-left: 10px;" width="400px" | ||
| Quick links | |||
|- | |||
| | |||
* [[Mysql/CheatSheet]] | |||
* [[Mysql]] | |||
|} | |||
== Commit() == | |||
Changes to the database require a commit(), unless a "with" statement is used! | |||
== Examples == | |||
* connect | |||
<pre> | |||
import pymysql | |||
db = pymysql.connect(host=localhost, port=3306, user="root", password="1234") | |||
</pre> | |||
* show version | |||
<pre> | |||
with db: | |||
cursor = db.cursor() | |||
cursor.execute("SELECT VERSION()") | |||
version = cursor.fetchone() | |||
print("Database version: {}".format(version[0])) | |||
</pre> | |||
* create database | |||
<pre> | |||
try: | |||
with db: | |||
cursor = db.cursor() | |||
cursor.execute("CREATE DATABASE carsearch") | |||
#db.commit() -> not needed as we use "with" | |||
except Exception as e: | |||
print(e) | |||
</pre> | |||
== Connection == | |||
<pre> | |||
db = pymysql.connect(host=localhost, port=3306, user="root", password="1234") | |||
</pre> | |||
* parameters: | |||
** host | |||
** port (default: 3306) | |||
** user | |||
** password | |||
** autocommit (default: false) | |||
* db.commit() | |||
* db.close() | |||
* db.rollback() #rollback current transaction | |||
== Cursor == | |||
* cursor.execute("CREATE DATABASE carsearch") | |||
* cursor.close() | |||
* cursor.fetchone() | |||
* cursor.fetchmany() | |||
* cursor.fetchall() | |||
== Documentation == | |||
* https://pymysql.readthedocs.io/en/latest/modules/index.html |
Latest revision as of 13:45, 19 June 2020
Quick links |
Commit()
Changes to the database require a commit(), unless a "with" statement is used!
Examples
- connect
import pymysql db = pymysql.connect(host=localhost, port=3306, user="root", password="1234")
- show version
with db: cursor = db.cursor() cursor.execute("SELECT VERSION()") version = cursor.fetchone() print("Database version: {}".format(version[0]))
- create database
try: with db: cursor = db.cursor() cursor.execute("CREATE DATABASE carsearch") #db.commit() -> not needed as we use "with" except Exception as e: print(e)
Connection
db = pymysql.connect(host=localhost, port=3306, user="root", password="1234")
- parameters:
- host
- port (default: 3306)
- user
- password
- autocommit (default: false)
- db.commit()
- db.close()
- db.rollback() #rollback current transaction
Cursor
- cursor.execute("CREATE DATABASE carsearch")
- cursor.close()
- cursor.fetchone()
- cursor.fetchmany()
- cursor.fetchall()