how to connect MySQL database to input function - python

I'm building a program, where the user input an enterprise's name to get the code running.
I would like the user to pick the enterprise name in a drop down list, but currently i dont have a GUI to make it work.
so for now, I would like to connect the input function to the SQL database enterprises name column.
I already connected SQL to my python code... but how do I connect MySQL to an input function? I want the user to be able to get the information from the database
MY SQL CONNECTION :
import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="nn", passwd="passpass")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM listedatabase.entreprises_inspecteurs")
for row in mycursor.fetchall():
print (row[1])
mydb.close()
python:
enterprise_name = input()
Thank you for helping
I tried this but no luck:
mydb = mysql.connector.connect(host="localhost", user="nn", passwd="passpass")
mycursor = mydb.cursor()
enterprise_name = input()
mycursor.execute("SELECT n_fabricant FROM listedatabase.entreprises_inspecteurs", (enterprise_name,))
data = mycursor.fetchall()
if data:
code goes there
else:
print('data not found in database')

mydb = mysql.connector.connect(host="localhost", user="nn", passwd="passpass")
mycursor = mydb.cursor()
enterprise_name = input()
mycursor.execute("""SELECT n_fabricant FROM listedatabase.entreprises_inspecteurs WHERE n_fabricant = %s"""(event_inspecteur,))
data = mycursor.fetchall()
if data:
code goes there
else:
print('data not found in database')

Related

pymysql error message (INSERT INTO function)

I encountered error message (INVALID SYNTAX) and have no idea why it happens.
Please help to figure it out.
import pymysql
db = pymysql.connect(host='localhost', port=3306, user='root', passwd='xxxxxxxx', db='ecommerce', charset='utf8')
ecommerce = db.cursor()
for index in range(10):
product_code = 215673140 + index +1
sql=INSERT INTO product VALUES(str(product_code),'sample data1','sample date2','sample data3'); ----> here's error point.
ecommerce.execute(sql)
db.commit()
db.close()
Try this. You have to enclose INSERT INTO ... inside " ". Also, don't use ; after the statement.
I suggest you should use %s. That way, you can insert any value inside that column
import pymysql
db = pymysql.connect(host='localhost', port=3306, user='root', passwd='xxxxxxxx', db='ecommerce', charset='utf8')
ecommerce = db.cursor()
for index in range(10):
product_code = 215673140 + index +1
sql = "INSERT INTO product VALUES (%s, %s,%s,%s,%s)"
val = (str(product_code),'sample data1','sample date2','sample data3')
ecommerce.execute(sql, val)
db.commit()
db.close()

Get separated string with a comma from a table

I trying to get separate strings from a column in a table. If I output them without anything they are looking like this:
('https://google.com',)
('http://example.com',)
('http://example.com,http://google.cpm',)
('http://example.com, http://google.cpm',)
('google.com, example.cpm',)
('google.com,example.com',)
('google.com, google.com',)
I want to check all off them with a function, if they are online or offline.
Here is my current script:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
database="python1"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT test1 FROM test2")
myresult = mycursor.fetchall()
for x in myresult:
x = .split(",")
return x
print(x)
I dont know how to fix this.
Thanks in advance
If you're trying to write a function that returns the parts of the names as individual items, you can do that:
def getUrls(mydb):
mycursor = mydb.cursor()
mycursor.execute( "SELECT test1 FROM test2" )
for row in mycursor.fetchAll():
for part in row[0].split(','):
yield part

Python and MySQL - fetchall() doesn't show any result

I have a problem getting the query results from my Python-Code. The connection to the database seems to work, but i always get the error:
"InterfaceError: No result set to fetch from."
Can somebody help me with my problem? Thank you!!!
cnx = mysql.connector.connect(
host="127.0.0.1" ,
user="root" ,
passwd="*****",
db="testdb"
)
cursor = cnx.cursor()
query = ("Select * from employee ;")
cursor.execute(query)
row = cursor.fetchall()
If your problem is still not solved, you can consider replacing the python mysql driver package and use pymysql.
You can write code like this
#!/usr/bin/python
import pymysql
db = pymysql.connect(host="localhost", # your host, usually localhost
user="test", # your username
passwd="test", # your password
db="test") # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
query = ("SELECT * FROM employee")
# Use all the SQL you like
cur.execute(query)
# print all the first cell of all the rows
for row in cur.fetchall():
print(row[0])
db.close()
This should be able to find the result you want
add this to your code
for i in row:
print(i)
you did not print anything which is why that's not working
this will print each row in separate line
first try to print(row),if it fails try to execute using the for the loop,remove the semicolon in the select query statement
cursor = connection.cursor()
rows = cursor.execute('SELECT * FROM [DBname].[dbo].TableName where update_status is null ').fetchall()
for row in rows:
ds = row[0]
state = row[1]
here row[0] represent the first columnname in the database
& row[1] represent the second columnname in the database & so on

Get list without JSON-like style mysql python

I am building a POS (point of sale) in python with MySQL!
I want to list all articles, but I get the JSON-like output.
My code:
import mysql.connector
print('eXperience POS\nArtikli:')
posdb = mysql.connector.connect\
(
user='root',
password='',
host='127.0.0.1',
database='experiencepos'
)
try:
cursor = posdb.cursor()
cursor.execute('SELECT * FROM artikli')
sviartikli = cursor.fetchall()
print(sviartikli)
finally:
posdb.close()
I think you're confusing JSON output with it printing a dict. Each item in the cursor returns a dict containing the item's fields. Since you did not show the example output I'll just use a name and description field for example. This is what I think you're looking for though. Also you may want to just loop through the cursor as printing the entire cursor would just print a list of dicts with all the items.
import mysql.connector
print('eXperience POS\nArtikli:')
posdb = mysql.connector.connect\
(
user='root',
password='',
host='127.0.0.1',
database='experiencepos'
)
try:
cursor = posdb.cursor()
cursor.execute('SELECT * FROM artikli')
for sviartikli in cursor:
name = sviartikli['name'] #example field
description = sviartikli['description'] #another example field
print("Name: {} Description: {}")
finally:
posdb.close()

Python - SQLite3 - Update not working via input

I try to Update my DB via Input.
import sqlite3
conn = sqlite3.connect('datenbank.db')
print ("Opened database successfully")
kunde1 = input("Der Kundename: ")
anzahl1 = input("Anzahl Bewertung: ")
conn.execute('''UPDATE kundenname SET anzahl = ? WHERE kundename = ?''',
(anzahl1, kunde1))
conn.commit
it dosent Show any Errors.. but it get not updated in DB?
Thanks a lot !
conn.commit does not call commit, rather, it is merely accessing its instance. Therefore, a simple commit call and a file close should fix the problem:
import sqlite3
conn = sqlite3.connect('datenbank.db')
print ("Opened database successfully")
kunde1 = input("Der Kundename: ")
anzahl1 = input("Anzahl Bewertung: ")
conn.execute('''UPDATE kundenname SET anzahl = ? WHERE kundename = ?''', (anzahl1, kunde1))
conn.commit()
conn.close()
since you are inputting data in the middle of the execution sequence, it may be better to use a contextmanager:
import contextlib
#contextlib.contextmanager
def update_database(kunde1, anzahl1):
conn = sqlite3.connect('datenbank.db')
print ("Opened database successfully")
yield conn #can be used later to update database in or outside the scope of "with"
conn.execute('''UPDATE kundenname SET anzahl = ? WHERE kundename = ?''', (anzahl1, kunde1))
conn.commit()
conn.close()
with update_database(input("Der Kundename: "), input("Anzahl Bewertung: ")) as b:
pass #do something after

Categories

Resources