Having trouble creating a MySQL database with python - python

I can't seem to figure out why my code won't create a MySQL table.
Everything seems ok to me, although my knowledge is limited.
import mysql.connector
import bot_keys as bk
conn = mysql.connector.connect(
host = bk.dbHost,
user = bk.dbUser,
password = bk.dbPass,
database = bk.dbName
)
mycursor = conn.cursor()
def create_table():
sql_fs1 = ("SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';"
"SET AUTOCOMMIT = 0;START TRANSACTION;"
"SET time_zone = '+00:00';"
"CREATE TABLE `test_table`(`id` int(10) NOT NULL PRIMARY KEY "
"AUTO_INCREMENT,`date_added` timestamp NOT NULL DEFAULT "
"CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,`test_info` "
"varchar(10) NOT NULL,`xxx` varchar(255) NOT NULL);")
mycursor.execute(sql_fs1, multi=True)
conn.commit()
create_table()
Can anyone point out where I am failing? Thanks in advance.

I would first check to see if your connection is actually working...
if conn.is_connected():
db_Info = conn.get_server_info()
print("Connected to MySQL Server version ", db_Info)
This assumes your bot keys have been properly parameter-ized, if i were you I would attempt to initially run w hard coded values, then parameter-ize once youve successfully run things....

The error will go away if you delete the line
conn.commit
The create table command causes an implicit commit,
https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html

Related

sqlite database didn't update table in my flask webhook python code

I try to update my sqlite database using flask webhook.
It seems commands line work fine if I type manually in the python console but my flask webhook didn't update my SQLite database. It seems the apps fail at the "cursor.execute()" line.
here is my webhook code:
#app.route('/trendanalyser', methods=['POST'])
def trendanalyser():
data = json.loads(request.data)
if data['passphrase'] == config.WEBHOOK_PASSPHRASE:
#Init update variables
tastate = data['TrendAnalyser']
date_format = datetime.today()
date_update = date_format.strftime("%d/%m/%Y %H:%M:%S")
update_data = ((tastate), (date_update))
#Database connection
connection = sqlite3.connect('TAState15min.db')
cursor = connection.cursor()
#Database Update
update_query = """Update TrendAnalyser set state = ?, date = ? where id = 1"""
cursor.execute(update_query, update_data)
connection.commit()
return("Record Updated successfully")
cursor.close()
else:
return {"invalide passphrase"}
Can you please tell me what's wrong with my code ?
if it's can help, here is my database structure (my db creation):
#Database connection
conn = sqlite3.connect("TAState15min.db")
cursor = conn.cursor()
#Create table
sql_query = """ CREATE TABLE TrendAnalyser (
id integer PRIMARY KEY,
state text,
date text
)"""
cursor.execute(sql_query)
#Create empty row with ID at 1
insert_query = """INSERT INTO TrendAnalyser
(id, state, date)
VALUES (1, 'Null', 'Null');"""
cursor.execute(insert_query)
conn.commit()
#Close database connexion
cursor.close()
**I finally found the issue, webhooks need the full path to the SQLite database to work fine. I just start to code in python, it was a noob issue... **
I finally found the issue, webhooks need the full path to the SQLite database to work fine. I just start to code in python, it was a noob issue...

Unable to INSERT with Pymysql (incremental id changes though)

When I'm using pymysql to perform operations on MySQL database, it seems that all the operations are temporary and only visible to the pymysql connection, which means I can only see the changes through cur.execute('select * from qiushi') and once I cur.close() and conn.close() and log back in using pymysql, everything seems unchanged.
However, when I'm looking at the incremental id numbers, it does increased, but I can't see the rows that were inserted from pymysql connection. It seems that they were automatically deleted?!
Some of my code is here:
import pymysql
try:
conn = pymysql.connect(host='127.0.0.1',port=3306,user='pymysql',passwd='pymysql',charset='utf8')
cur = conn.cursor()
#cur.execute('CREATE TABLE qiushi (id INT NOT NULL AUTO_INCREMENT, content_id BIGINT(10) NOT NULL, content VARCHAR(1000), created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(id));')
#cur.execute('DESCRIBE content')
#cur.fetchall()
cur.execute('USE qiushibaike')
for _ in range(0,len(content_ids)):
cur.execute("INSERT INTO qiushi (content,content_id) VALUES (\"%s\",%d)"%(jokes[_],int(content_ids[_])))
finally:
cur.close()
conn.close()
I solved the problem by myself...
Because the config is automatically committed, so after each SQL sentence we should commit the changes.
Approach 1:
add cur.commit() after the cur.execute()
Approach 2:
edit the connection config, add autocommit=True

Python Flask and sqlite3 commit not working

This is just a small bite of my code but I hope it will be enough so solve my problem. Allow me to explain first.
So I am attempting to store information in a database using python and sqlite3. I can store stuff in the database but the file size of the database never increases and after a restart the database is cleared. I know that .commit works because I have used it in the past but it is not working now. My assumption is that I am out of scope of the database and I don't have the ability to write. Once again, my code runs and provides no errors, but it will not actually write to the database.
My Connection and Init Code:
def connect_db():
conn = sqlite3.connect(app.config['DATABASE'])
conn.row_factory = sqlite3.Row
return conn
def init_db():
conn = connect_db()
cursor = conn.cursor()
sql = 'create table if not exists users (id integer primary key autoincrement, username text not null, password text not null, admin boolean not null)'
cursor.execute(sql)
conn.commit()
So this code connects to the database and gets everything setup.
Here is a small portion of my code to add an item to the database. It works and it will add items to the "database" but the file size of the database does not increase and if I restart it wont see the new items. But as long as the application is open I have access to the items.
#app.route('/user/', methods=['GET', 'POST'])
def users():
conn = connect_db()
cursor = conn.cursor()
isAdmin = False
if (request.form.get('adminuser') != None):
isAdmin = True
cursor.execute('insert into users (username, password, admin) values (?, ?, ?)',
[request.form['username'], request.form['password'], isAdmin])
conn.commit()
return redirect(url_for('index'))
Edit I left This Out
DATABASE = '/tmp/database.db'
Edit A Crazy Simple Mistake.
Change
DATABASE = '/tmp/database.db'
To
DATABASE = './tmp/database.db'
There is an error in this line:
DATABASE = '/tmp/database.db'
Use this instead:
DATABASE = './tmp/database.db'

Empty table in MySQL even though Python can insert data into table

I'm new to mySQL and Python.
I have code to insert data from Python into mySQL,
conn = MySQLdb.connect(host="localhost", user="root", passwd="kokoblack", db="mydb")
for i in range(0,len(allnames)):
try:
query = "INSERT INTO resumes (applicant, jobtitle, lastworkdate, lastupdate, url) values ("
query = query + "'"+allnames[i]+"'," +"'"+alltitles[i]+"',"+ "'"+alldates[i]+"'," + "'"+allupdates[i]+"'," + "'"+alllinks[i]+"')"
x = conn.cursor()
x.execute(query)
row = x.fetchall()
except:
print "error"
It seems to be working fine, because "error" never appears. Instead, many rows of "1L" appear in my Python shell. However, when I go to MySQL, the "resumes" table in "mydb" remains completely empty.
I have no idea what could be wrong, could it be that I am not connected to MySQL's server properly when I'm viewing the table in MySQL? Help please.
(I only use import MySQLdb, is that enough?)
use commit to commit the changes that you have done
MySQLdb has autocommit off by default, which may be confusing at first
You could do commit like this
conn.commit()
or
conn.autocommit(True) Right after the connection is created with the DB

Database connectivity succeeds but unable to run query

I am able to connect Python 3.4 and Postgres but I am the query is not successfully getting executed. For e.g, the table below is not getting created
import psycopg2
from psycopg2 import connect
try:
conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' password='postgres'")
print("Database connected!")
cur = conn.cursor()
cur.execute("""CREATE TABLE DEPARTMENT(
ID INT PRIMARY KEY NOT NULL,
DEPT CHAR(50) NOT NULL,
EMP_ID INT NOT NULL
)""")
except:
print("I am unable to connect to the database")
Just add
conn.commit()
after you've run the execute.
Relational databases have the concept of transaction, which happen (if at all) "atomically" (all-or-none). You need to commit a transaction to actually make it take place; until you've done that, you keep the option to rollback it instead, to have no changes made to the DB if you've found something iffy on the way.

Categories