Home > Mobile >  How connect to database and get data via python like in R
How connect to database and get data via python like in R

Time:08-29

I new in python. I need connect to mysql database and get data. Before that, I easily took data via R using rodbslike this.

library(DBI)
library(RMySQL)
db_user = 'k'
db_password = 'F6'
db_name = 'meg'
db_table = 'dat'
db_host = 'my.g2s' # for local access
db_port = 3306

# 3. Read data from db
mydbV7 = dbConnect(MySQL(), user = db_user, password = db_password,
                     dbname = db_name, host = db_host, port = db_port)
sV7 = paste0("select * from ", db_table)

rsV7 = dbSendQuery(mydbV7, sV7)

df =  fetch(rsV7, n = -1)

but when i tried to implement the same principle in python i get errors

import pyodbc

>>> db_user = 'k'
>>> db_password = 'F6'
>>> db_name = 'meg'
>>> db_table = 'dat'
>>> db_host = 'my.g2s' # for local access
>>> db_port = 3306
>>> mydbV7 = dbConnect(MySQL(), user = db_user, password = db_password,
...                      dbname = db_name, host = db_host, port = db_port)

 File "<stdin>", line 2
    ...                      dbname = db_name, host = db_host, port = db_port)
                             ^
SyntaxError: positional argument follows keyword argument

How can i correct get data via python 3.9? As always, I appreciate any of your help.

CodePudding user response:

As describe in the MySQL documentation, you can import mysql.connector and then use :

cnx = mysql.connector.connect(user = 'scott', 
                              password = 'password',
                              host = '127.0.0.1',
                              database = 'employees')

Of course, you have to change the values with yours. cnx will then represent the connection with your database.

  • Related