Pythonista.
I am doing a Mysql database that first ask the user for the data base name. that works.
Once database is created it doest create the tables put prints out this error:
if not self._connection:
ReferenceError: weakly-referenced object no longer exists
Here is the code:
'''
import mysql.connector
# Create database
database_name = input(">> ")
db = mysql.connector.connect(
host='localhost',
user='root',
passwd='Mysql2021',)
my_cursor = db.cursor()
my_cursor.execute("CREATE DATABASE IF NOT EXISTS %s" %database_name)
db = mysql.connector.connect(
host='localhost',
user='root',
passwd='Mysql2021',
database=database_name)
# Create table
my_cursor.execute("CREATE TABLE test1 (firstname VARCHAR(255),lastname VARCHAR(255)")
'''
thank you for your help.
You are missing an opening bracket on the database name. It should ideally be like this:
my_cursor = db.cursor()
my_cursor.execute("CREATE DATABASE IF NOT EXISTS %s" %(database_name)
With the full code looking like this:
import mysql.connector
# Create database
database_name = input(">> ")
db = mysql.connector.connect(
host='localhost',
user='root',
passwd='Mysql2021',)
my_cursor = db.cursor()
my_cursor.execute("CREATE DATABASE IF NOT EXISTS %s" %(database_name)
db = mysql.connector.connect
host='localhost',
user='root',
passwd='Mysql2021',
database=database_name)
# Create table
my_cursor.execute("CREATE TABLE test1 (firstname VARCHAR(255),lastname VARCHAR(255)")
Related
I am trying to update my mariadb table via python code .While compile the query nothing happen in my database. please check below code and let me know where i made mistake in update function
import mariadb
connection= mariadb.connect(user="user1", database="db1", host="ippp" ,password="pass")
cursor= connection.cursor()
cursor.execute("UPDATE product_options_combinations SET quantity=5944 WHERE item_code ='31628'")
cursor.close()
connection.close()
Hello here I have a clean code example for you. How to update it.
import pymysql
# Create a connection object
# IP address of the MySQL database server
Host = "localhost"
# User name of the database server
User = "user"
# Password for the database user
Password = ""
database = "GFG"
conn = pymysql.connect(host=Host, user=User, password=Password, database)
# Create a cursor object
cur = conn.cursor()
query = f"UPDATE PRODUCT SET price = 1400 WHERE PRODUCT_TYPE = 'broadband'"
cur.execute(query)
#To commit the changes
conn.commit()
conn.close()
You just need to add connection.commit() to your code, but I recommend you use a parametrized SQL preferably with a list of tuples,more of which might be added if needed, along with cursor.executemany() as being more performant for DML statements such as
import mariadb
connection= mariadb.connect(user="user1",
password="pass",
host="ippp",
port=3306,
database="db1")
cursor= connection.cursor()
dml="""
UPDATE product_options_combinations
SET quantity=%s
WHERE item_code =%s
"""
val=[
(5944,'31628')
]
cursor.executemany(dml,val)
connection.commit()
cursor.close()
connection.close()
Are you sure that the connection is working properly?
Have you tried to implement a try and catch routine to print mariadb errors?
Something like this:
# Connect to MariaDB Platform
import mariadb
try:
conn = mariadb.connect(
user="user",
password="password",
host="xx.xx.xx.xx",
port=3306,
database="db_name"
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
So currently I'm able to perform mysql queries by simply doing
import mysql.connector
from mysql.connector import connect, Error
with connect(
host="localhost",
user="user",
password="password",
) as connection:
select_query = """
SELECT * FROM MY_TABLE
"""
with connection.cursor() as cursor:
cursor.execute(select_query)
Is there a way to do this but without the "SQL"
Something like this pseudo code
table = Table("MY_TABLE")
return table.select_all()
I'm connecting to a postgres database in Heroku and trying to create a table. I run the code below but no new table shows up in the database.
import psycopg2
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
create_table = (""" CREATE TABLE test_table (account_address__c varchar); """)
cur = conn.cursor()
cur.execute(create_table)
conn.close()
Can you help?
Thank you!
I forgot to add
conn.commit()
.
cur = conn.cursor()
cur.execute(create_table)
conn.commit()
conn.close()
After running the following code, no results are coming from the MySQL command:
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",password="Abhi#123")
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
Take a look at this answer: https://stackoverflow.com/a/20959654/7420301
Maybe try something like this...
import mysql.connector mydb = mysql.connector.connect(host="localhost",
user="root",
password="Abhi#123")
try:
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
all_my_databases = mycursor.fetchall()
print all_my_databases
finally:
mydb.close()
I want to use the python MySQLdb to access a remote MySQL server with --local-infile flag in order to be able to load data from a local file. (as mentioned in this question Importing CSV to MySQL table returns an error #1148)
I use
db = MySQLdb.connect(host="127.0.0.1", port=3307, user="someuser", passwd="password", db="sql_db")
to create a database connection. How do I mimic mysql -u username -p dbname --local-infile using MySQLdb
I know this is late for the initial question, but if someone comes here looking for the same you can do this:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
allow_local_infile=True,
)
Here you can check the docs for aditional flags: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
If you want to set it as a DB config rather than in the connection, you can do it like this:
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
)
mycursor = mydb.cursor()
try:
command = "SET GLOBAL local_infile = 'ON';"
mycursor.execute(command)
except mysql.connector.errors.DatabaseError:
pass
You can put your DB configurations in to a local file, and then read it when using.
config.ini
[MySQL]
host=192.168.20.28
user=root
password=123456
db_name=ovp_global
charset=utf8
py code:
import MySQLdb
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open("config.ini", "r"))
def get_connection():
host = config.get('MySQL', 'host')
user = config.get('MySQL', 'user')
passwd = config.get('MySQL', 'password')
db = config.get('MySQL', 'db_name')
charset = config.get('MySQL', 'charset')
return MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, charset=charset)