Validation of inputs in database using python in mariadb-connector - python

I want to know how to validate inputs using MariaDB Connector/Python. It just like a signup page that won't allow to use same username.
PSEUDOCODE GO LIKE THIS
CHECKIF DATA IN DATABASE
IF USER_INPUT == DATA IN DATABASE
PRINT("DATA ALREADY EXIST!")
ELSEIF
INSERT DATA IN DATABASE
PRINT("DATA ADDED")
I hope you get what am I trying to do. Thank you in advance for your response.
I tried doing it in this way
conn = mariadb.connect(host="127.0.0.1",
user="root",
database="blankshot",
passwd="")
#Get Cursor
cur = conn.cursor()
query = "INSERT INTO testtable(test) VALUES('"+strloc+"')"
CheckQuery = "SELECT test FROM testtable where test='"+strloc+"'"
cur.execute(CheckQuery)
cur.fetchone()
if location == '':
print("Don't leave it blank")
elif len(strloc) != 0:
if(cur.next()):
print("Data already exist")
else:
cur.execute(query)
inf = cur.lastrowid
cur.close()
except mariadb.Error as e:
print(f"Error connecting to MariaDb platform:{e}")
conn.commit()
print(f"Last Inserted ID: ", str(inf))
conn.close()
Doing this was nothing happened. It still records the same inputs

Related

python psycopg2 can't load the table in the database

I successfully access the database, however, I can't load the table inside the database. I am quite sure that the name of the table is correct, the database is a mimic iii database. Please give me a helping hand, thanks a lot!
import psycopg2
try:
connection = psycopg2.connect(user="postgres",
password="xxxxxxx",
host="localhost",
port="5432",
database="mimic")
cursor = connection.cursor()
postgreSQL_select_Query = "select * from admissions"
cursor.execute(postgreSQL_select_Query)
print("Selecting rows from mobile table using cursor.fetchall")
admissions_records = cursor.fetchall()
print("Print each row and it's columns values")
for row in admissions_records:
print("x = ", row[0], )
print("y = ", row[1])
print("z = ", row[2], "\n")
except (Exception, psycopg2.Error) as error:
print("Error while fetching data from PostgreSQL", error)
finally:
# closing database connection.
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
Here's the output:
Error while fetching data from PostgreSQL relation "admissions" does not exist
LINE 1: select * from admissions
^
PostgreSQL connection is closed

Lost connection to MySQL server at 'localhost:3306', system error: Connection not available

servlet2.py
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='localhost',
database='*project',
user='*****',
password='*****',
)
print("Connection Established")
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('Somethign is wrong with username or password')
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print('Database does not exist')
else:
print(e)
c = connection.cursor()
def insertSQL(user):
mySql_insert_query = "INSERT INTO python_project.test (Name) VALUES (?)", (user)
print("user:", user)
c.execute(mySql_insert_query)
print(c.rowcount, "Record inserted successfully into test table")
def username():
user = input("Please Enter Your Name: " )
insertSQL(user)
test_script.py
import servlet2
servlet2.username()
I was able to established connection to the database, however, once I enter name. It will fail to connect and prompt this error.
OperationalError: Lost connection to MySQL server at 'localhost:3306', system error: Connection not available.
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='127.0.0.1',
database='python_project',
user='root',
password='catdog123',
)
print("Connection Established")
#cursor = connection.cursor()
#cursor.execute("""INSERT INTO test (Name) VALUES ('harry')""")
#connection.commit()
#cursor.close()
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('Somethign is wrong with username or password')
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print('Database does not exist')
else:
print(e)
c = connection.cursor()
def insertSQL(user):
#mySql_insert_query = """INSERT INTO test (Name) VALUES (?)""", user
print("user:", user)
print(c.rowcount, "Record inserted successfully into test table")
c.execute("""INSERT INTO test (Name) VALUES ('{}')""".format(user))
connection.commit()
def username():
user = input("Please Enter Your Name:" )
insertSQL(user)
I manage to solve it by changing the insert statement VALUES to ('{}').format(user)

How to delete data from database that has been published to the cloud?

I am generating dummy data in the database and then publishing to cloud.
As soon as it is published, I want to delete that entry from the database.
I understand that I need to send the 'mid' value in the publish method then call deleteFromDb() function. But mid is always 1, even though I return ret.mid=index. Index is the primary key retrieved from the database.
def on_publish(unused_client,unused_userdata,mid):
print('on_publish')
deleteFromDb(mid)
def main() :
TableSchema="""
create table if not exists heartbeat(
id integer primary key autoincrement,
Date_Time text,
Heartbeat text
);
"""
while True:
conn = sqlite3.connect(dbFile)
print("Connected to db")
conn.execute('pragma foreign_keys = on')
conn.commit()
curs = conn.cursor()
print "Writing to db..."
sqlite3.complete_statement(TableSchema)
curs.executescript(TableSchema)
conn.commit()
rectime=strftime("%Y-%m-%d %H:%M:%S", gmtime())
res="ON"
curs.execute("insert into heartbeat (Date_Time, Heartbeat)
values (?,?)",[rectime,res])
conn.commit()
print "Inserted Heartbeat Data into Database."
for row in curs.execute("select * from heartbeat"):
index=row[0]
continue
conn.commit()
encoded_row=''
encoded_row=json.dumps(row) #Dumped in the form of str
print encoded_row
client = mqtt.Client(client_id=_CLIENT_ID)
client.username_pw_set (username='unused', password=create_jwt(project_id, ssl_private_key_filepath, ssl_algorithm))
client=mqtt.Client()
client.on_connect = on_connect
client.on_publish=on_publish
client.on_message = on_message
client.tls_set(ca_certs=root_cert_filepath)
client.connect('mqtt.googleapis.com', 8883,60)
client.loop_start()
ret=client.publish(_MQTT_TOPIC,encoded_row,qos=1)
time.sleep(0.5)
ret.mid=index
client.loop_stop()
#print(ret.mid)
curs.close()
conn.close()
I am assuming you are using sqlite3 so you need to connect and execute a delete statement to delete and then commit() to make changes you saved. Try like this
import sqlite3
deleteFromDb(mid):
con=sqlite3.connect("mydatabase.db") #your db name
cursor=con.cursor()
cursor.execute("DELETE FROM TABLE_NAME WHERE ID = %s" % mid)
con.commit()
con.close()

PyMySQL not Inserting Data

I have a piece of code which is taking Windows logs and inserting various pieces of information into an mySQL database. The code is running perfectly with no errors, but does not actually input the data into the table. The table remains blank. I pulled my mySQL syntax from an example with some modification, so I'm not entirely sure what is going wrong. I have a feeling it has either to do with the data types, or some changes I made to the syntax.
import sys
import pymysql
import pymysql.cursors
import win32evtlog # requires pywin32 pre-installed
import win32evtlogutil
import time
server = 'localhost' # name of the target computer to get event logs
logtype = 'System' # 'Application' # 'Security'
hand = win32evtlog.OpenEventLog(server,logtype)
flags =
win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
events = win32evtlog.ReadEventLog(hand, flags,0)
while True:
for event in events:
evt_tp = event.EventType
if evt_tp != (1 or 2 or 8):
eve_cat = str(('Event Category:', event.EventCategory))
eve_timegen = str(('Time Generated:', event.TimeGenerated))
eve_srcnm = str(('Source Name:', event.SourceName))
eve_id = str(('Event ID:', event.EventID))
eve_typ = str(('Event Type:', event.EventType))
data = event.StringInserts
if data:
print ('Event Data:')
for msg in data:
print(msg)
print(type(eve_cat))
print(type(eve_timegen))
print(type(eve_srcnm))
print(type(eve_id))
print(type(eve_typ))
print(type(data))
time.sleep(10)
else:
eve_cat = ('Event Category:', event.EventCategory)
eve_timegen = ('Time Generated:', event.TimeGenerated)
eve_srcnm = ('Source Name:', event.SourceName)
eve_id = ('Event ID:', event.EventID)
eve_typ = ('Event Type:', event.EventType)
data = event.StringInserts
print('There were no errors found')
print(eve_cat)
print(eve_timegen)
print(eve_srcnm)
print(eve_id)
print(eve_typ)
print(data)
time.sleep(10)
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='ptest',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `win_logs` (`Category`, `TimeGenerated`, 'SourceName',
'EventID', 'Type') VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, (eve_cat, eve_timegen, eve_srcnm, eve_id, eve_typ))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `Type` FROM `win_logs` WHERE `Category`=%s"
cursor.execute(sql, ('webmaster#python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
I can be very wrong.
But this is python.
Indentation matter.
Try just:
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `win_logs` (`Category`, `TimeGenerated`, 'SourceName`, 'EventID', 'Type') VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, (eve_cat, eve_timegen, eve_srcnm, eve_id, eve_typ))
I guess your cursor is out of with scope

Querying results from mysql DB to a list

Eventually I would like to output the hosts to a list.
try:
cnx = mysql.connector.connect(user='root', password='passwd',
database='some_db')
cursor = cnx.cursor()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
retrieveQuery = ("SELECT host_name,product from server")
cursor.execute(retrieveQuery)
for host,prod in cursor:
print ("{},{}".format(host,prod))
Result looks good: [host1,PowerEdge]
retrieveQuery = ("SELECT host_name from server")
cursor.execute(retrieveQuery)
for host in cursor:
print ("{}".format(host))
Result: (u'host1',)
Why am I seeing (u',) with the same code but when just one column is selected ?
Any help is much appreciated
Your cursor row result is always tuple type, try:
for row in cursor:
print ("{}".format(row.host_name))
or
for host, in cursor:
print ("{}".format(host))

Categories

Resources