Skip to content

Commit 7d089b7

Browse files
authored
Merge pull request #180212 from shreyaaithal/python-quickstarts
Make corrections to Connect using Python Quickstart
2 parents 3c859d1 + 8f47c25 commit 7d089b7

File tree

1 file changed

+119
-9
lines changed

1 file changed

+119
-9
lines changed

articles/mysql/connect-python.md

Lines changed: 119 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ ms.devlang: python
99
ms.topic: quickstart
1010
ms.date: 10/28/2020
1111
---
12-
12+
1313
# Quickstart: Use Python to connect and query data in Azure Database for MySQL
1414

1515
[!INCLUDE[applies-to-mysql-single-server](includes/applies-to-mysql-single-server.md)]
@@ -68,6 +68,19 @@ Get the connection information you need to connect to Azure Database for MySQL f
6868

6969
:::image type="content" source="./media/connect-python/azure-database-for-mysql-server-overview-name-login.png" alt-text="Azure Database for MySQL server name 2":::
7070

71+
## Running the Python code samples
72+
73+
For each code example in this article:
74+
75+
1. Create a new file in a text editor.
76+
2. Add the code example to the file. In the code, replace the `<mydemoserver>`, `<myadmin>`, `<mypassword>`, and `<mydatabase>` placeholders with the values for your MySQL server and database.
77+
1. SSL is enabled by default on Azure Database for MySQL servers. You may need to download the [DigiCertGlobalRootG2 SSL certificate](https://cacerts.digicert.com/DigiCertGlobalRootG2.crt.pem) to connect from your local environment. Replace the `ssl_ca` value in the code with path to this file on your computer.
78+
1. Save the file in a project folder with a *.py* extension, such as *C:\pythonmysql\createtable.py* or */home/username/pythonmysql/createtable.py*.
79+
1. To run the code, open a command prompt or `bash` shell and change directory into your project folder, for example `cd pythonmysql`. Type the `python` command followed by the file name, for example `python createtable.py`, and press Enter.
80+
81+
> [!NOTE]
82+
> On Windows, if *python.exe* is not found, you may need to add the Python path into your PATH environment variable, or provide the full path to *python.exe*, for example `C:\python27\python.exe createtable.py`.
83+
7184
## Step 1: Create a table and insert data
7285

7386
Use the following code to connect to the server and database, create a table, and load data by using an **INSERT** SQL statement.The code imports the mysql.connector library, and uses the method:
@@ -76,29 +89,23 @@ Use the following code to connect to the server and database, create a table, an
7689
- [cursor.close()](https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-close.html) when you are done using a cursor.
7790
- [conn.close()](https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-close.html) to close the connection the connection.
7891

79-
> [!IMPORTANT]
80-
> - SSL is enabled by default. You may need to download the [DigiCertGlobalRootG2 SSL certificate](https://cacerts.digicert.com/DigiCertGlobalRootG2.crt.pem) to connect from your local environment.
81-
> - Replace the `<mydemoserver>`, `<myadmin>`, `<mypassword>`, and `<mydatabase>` placeholders with the values for your MySQL server and database.
82-
8392
```python
8493
import mysql.connector
8594
from mysql.connector import errorcode
8695

8796
# Obtain connection string information from the portal
8897

89-
[!INCLUDE[applies-to-mysql-single-server](includes/applies-to-mysql-single-server.md)]
9098
config = {
9199
'host':'<mydemoserver>.mysql.database.azure.com',
92100
'user':'<myadmin>@<mydemoserver>',
93101
'password':'<mypassword>',
94102
'database':'<mydatabase>',
95103
'client_flags': [mysql.connector.ClientFlag.SSL],
96-
'ssl_ca': '/var/wwww/html/DigiCertGlobalRootG2.crt.pem'
104+
'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.crt.pem'
97105
}
98106

99107
# Construct connection string
100108

101-
[!INCLUDE[applies-to-mysql-single-server](includes/applies-to-mysql-single-server.md)]
102109
try:
103110
conn = mysql.connector.connect(**config)
104111
print("Connection established")
@@ -144,6 +151,35 @@ Use the following code to connect and read the data by using a **SELECT** SQL st
144151
The code reads the data rows using the [fetchall()](https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchall.html) method, keeps the result set in a collection row, and uses a `for` iterator to loop over the rows.
145152

146153
```python
154+
import mysql.connector
155+
from mysql.connector import errorcode
156+
157+
# Obtain connection string information from the portal
158+
159+
config = {
160+
'host':'<mydemoserver>.mysql.database.azure.com',
161+
'user':'<myadmin>@<mydemoserver>',
162+
'password':'<mypassword>',
163+
'database':'<mydatabase>',
164+
'client_flags': [mysql.connector.ClientFlag.SSL],
165+
'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.crt.pem'
166+
}
167+
168+
# Construct connection string
169+
170+
try:
171+
conn = mysql.connector.connect(**config)
172+
print("Connection established")
173+
except mysql.connector.Error as err:
174+
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
175+
print("Something is wrong with the user name or password")
176+
elif err.errno == errorcode.ER_BAD_DB_ERROR:
177+
print("Database does not exist")
178+
else:
179+
print(err)
180+
else:
181+
cursor = conn.cursor()
182+
147183
# Read data
148184
cursor.execute("SELECT * FROM inventory;")
149185
rows = cursor.fetchall()
@@ -153,27 +189,101 @@ The code reads the data rows using the [fetchall()](https://dev.mysql.com/doc/co
153189
for row in rows:
154190
print("Data row = (%s, %s, %s)" %(str(row[0]), str(row[1]), str(row[2])))
155191

192+
# Cleanup
193+
conn.commit()
194+
cursor.close()
195+
conn.close()
196+
print("Done.")
156197
```
157198

158199
## Step 3: Update data
159200

160201
Use the following code to connect and update the data by using an **UPDATE** SQL statement. The code imports the mysql.connector library, and uses [cursor.execute()](https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html) method executes the SQL query against the MySQL database.
161202

162203
```python
204+
import mysql.connector
205+
from mysql.connector import errorcode
206+
207+
# Obtain connection string information from the portal
208+
209+
config = {
210+
'host':'<mydemoserver>.mysql.database.azure.com',
211+
'user':'<myadmin>@<mydemoserver>',
212+
'password':'<mypassword>',
213+
'database':'<mydatabase>',
214+
'client_flags': [mysql.connector.ClientFlag.SSL],
215+
'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.crt.pem'
216+
}
217+
218+
# Construct connection string
219+
220+
try:
221+
conn = mysql.connector.connect(**config)
222+
print("Connection established")
223+
except mysql.connector.Error as err:
224+
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
225+
print("Something is wrong with the user name or password")
226+
elif err.errno == errorcode.ER_BAD_DB_ERROR:
227+
print("Database does not exist")
228+
else:
229+
print(err)
230+
else:
231+
cursor = conn.cursor()
232+
163233
# Update a data row in the table
164-
cursor.execute("UPDATE inventory SET quantity = %s WHERE name = %s;", (200, "banana"))
234+
cursor.execute("UPDATE inventory SET quantity = %s WHERE name = %s;", (300, "apple"))
165235
print("Updated",cursor.rowcount,"row(s) of data.")
236+
237+
# Cleanup
238+
conn.commit()
239+
cursor.close()
240+
conn.close()
241+
print("Done.")
166242
```
167243

168244
## Step 4: Delete data
169245

170246
Use the following code to connect and remove data by using a **DELETE** SQL statement. The code imports the mysql.connector library, and uses [cursor.execute()](https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html) method executes the SQL query against the MySQL database.
171247

172248
```python
249+
import mysql.connector
250+
from mysql.connector import errorcode
251+
252+
# Obtain connection string information from the portal
253+
254+
config = {
255+
'host':'<mydemoserver>.mysql.database.azure.com',
256+
'user':'<myadmin>@<mydemoserver>',
257+
'password':'<mypassword>',
258+
'database':'<mydatabase>',
259+
'client_flags': [mysql.connector.ClientFlag.SSL],
260+
'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.crt.pem'
261+
}
262+
263+
# Construct connection string
264+
265+
try:
266+
conn = mysql.connector.connect(**config)
267+
print("Connection established")
268+
except mysql.connector.Error as err:
269+
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
270+
print("Something is wrong with the user name or password")
271+
elif err.errno == errorcode.ER_BAD_DB_ERROR:
272+
print("Database does not exist")
273+
else:
274+
print(err)
275+
else:
276+
cursor = conn.cursor()
173277

174278
# Delete a data row in the table
175279
cursor.execute("DELETE FROM inventory WHERE name=%(param1)s;", {'param1':"orange"})
176280
print("Deleted",cursor.rowcount,"row(s) of data.")
281+
282+
# Cleanup
283+
conn.commit()
284+
cursor.close()
285+
conn.close()
286+
print("Done.")
177287
```
178288

179289
## Clean up resources

0 commit comments

Comments
 (0)