I'm trying to connect to a external database but after trying to connect to the database, the whole script stops running. i'm trying to run it on a Raspberry PI 3. So after the attempt to connect to the database, it stops working. the test print does show up but the second one does not.
Script:
import MySQLdb
HOST = "host"
PORT = 3306
USER = "user"
PASS = "pass"
DATABASE = "databasename"
print("test")
db = MySQLdb.connect(HOST, USER, PASS, DATABASE)
print("test2")
cursor = db.cursor()
cursor.execute("SELECT * FROM Persoon")
data = cursor.fetchone()
print "database version :%s"% data
db.close()
Related
I am a beginner in python and mysql. I have a small application written in Python that connects to remote mysql server. There is no issues to connect and fetch data. It works fine then the code is outside a function. As I want to close and open connections, execute different queries from several functions inside my application, I would like to be able to call a function to establish a connection or run a query as needed. It seems that when I create an connection, that connection can not be used outside the function. I would like to implement something like this:
mydbConnection():
....
mydbQuery():
....
connected = mydbConnection()
myslq = 'SELECT *.......'
result = mydbQuery(mysql)
And so on...
Thanks for any direction on this.
import mysql.connector
from mysql.connector import Error
def mydbConnection(host_name, user_name, user_password):
connection = None
try:
connection = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=user_password
)
print("Connection to MySQL DB successful")
except Error as e:
print(f"The error '{e}' occurred")
return connection
connection = mydbConnection("localhost", "root", "")
In the above script, you define a function mydbConnection() that accepts three parameters:
host_name
user_name
user_password
The mysql.connector Python SQL module contains a method .connect() that you use in line 7 to connect to a MySQL database server. Once the connection is established, the connection object is returned to the calling function. Finally, in line 18 you call mydbConnection() with the host name, username, and password.
Now, to use this connect variable, here is a function:
def mydbQuery(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
print("Database created successfully")
except Error as e:
print(f"The error '{e}' occurred")
To execute queries, you use the cursor object. The query to be executed is passed to cursor.execute() in string format.
Create a database named db for your social media app in the MySQL database server:
create_database_query = "CREATE DATABASE db"
mydbQuery(connection, create_database_query)
I am using mysql.connector to connect to a mysql DB, while i can connect manually to the db using sql server management, if i try connecting via code, it returns this error after awhile :
mysql.connector.errors.OperationalError: 2055: Lost connection to MySQL server at 'host:1234', system error: 10054 An existing connection was forcibly closed by the remote host
These are the connection details :
connection = mysql.connector.connect(host='host',
port = '1234',
database='DBname',
user='Usr',
password='pwd')
If I create a local mysql DB, the connection works just fine.
I assume some security stuff is going on, anyone else had encountered this situation ? Anything that I'm doing wrong? Should I add anything to the connection.connect input ?
Full code for reference :
import mysql.connector
from mysql.connector import Error
connection = mysql.connector.connect(host='host',
port = '1234',
database='DBname',
user='Usr',
password='pwd')
sql_select_Query = "select * from TableName"
cursor = connection.cursor()
cursor.execute(sql_select_Query)
records = cursor.fetchall()
print("Total numb of rows selected is : ", cursor.rowcount)
print("\nPrinting each row")
for row in records:
print(row)
connection.close()
I am not able to connect to MySQL sever using python it gives and error which says
MySQLdb._exceptions.OperationalError: (1130, "Host 'LAPTOP-0HDEGFV9' is not allowed to connect to this MySQL server")
The code I'm using:
import MySQLdb
db = MySQLdb.connect(host="LAPTOP-0HDEGFV9", # your host, usually localhost
user="root", # your username
passwd="abcd13de",
db="testing") # name of the data base
cur = db.cursor()
cur.execute("SELECT * Employee")
for row in cur.fetchall():
print(row[0])
db.close()
This is an authorization problem not a connectivity problem. Is the db running locally? If not, confirm with the admin where it is hosted. If so, try changing the host parameter to 127.0.0.1?
As described here the admin can get the hostname by running:
select ##hostname;
show variables where Variable_name like '%host%';
If the connection was timing out you could try setting the connect_timeout kwarg but that's already None by default.
i want to connect MySQL in external server on Ubuntu. i already have Apache server in there and i have created table.i try to connect it form Raspberry Pi with python code but it doesn't work please help me
Import part
import bluetooth
import time
import mysql.connector
import MySQLdb
import os
import datetime
Connection part
#connect to db
db = MySQLdb.connect("133.2.206.154","kgam","password","kgam" )
#setup cursor
cursor = db.cursor()
sql = "SELECT * FROM user"
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
except:
print "Error: unable to fetch data"
Error
This is my error code
I am unable to connected to database in linux using psycopg2. I have postgresql installed in linux and my code is:
import psycopg2
def testEgg():
conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")
cur = conn.cursor()
cur.execute("CREATE TABLE egg ( num integer, data varchar);")
cur.execute("INSERT INTO egg values ( 1, 'A');")
conn.commit()
cur.execute("SELECT num from egg;")
row = cur.fetchone()
print row
cur.close()
conn.close()
testEgg()
And the I got the error:
psycopg2.OperationalError: FATAL: Ident authentication failed for user "postgres"
This code runs well in windows7 but got above mentioned error in linux.
Is there anything I need to do more in linux? Any suggestion will be appreciated.
Thank you.
It's not a problem due to your code, but due to the permission of the postgres user.
You should create a new user to access to your database and replace this :
conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")
by (replace <your_user> by your real user name ...)
conn = psycopg2.connect("dbname = myDatabase user = <your_user> port = 5432")
To create a new user on postgres, you can use the 'createuser' binary. The documentation is available here.