from tkinter import *
from tkinter import messagebox
import mysql.connector
mydb = mysql.connector.connect(host='localhost',user='root',passwd='Alok1823!',database='kbc')
mycursor = mydb.cursor()
tempuser='tarran09'
mycursor.execute("insert into `kbc`.`player` ('username') values (tempuser) ")
How do I add values to a table from Python editor. The values are not direct values but rather stored in variables. I don't know what the contents of that variable are at any given moment. So how do add the value of these variables into one the tables of mySQL database?
If the variable is string then:
import mysql.connector
mydb = mysql.connector.connect(host='localhost',user='root',passwd='Alok1823!',database='kbc')
mycursor = mydb.cursor()
tempuser='tarran09'
mycursor.execute(f"insert into kbc.player (username) values ('{tempuser}')")
mydb.commit()
If you are using python version < 3.6, then
mycursor.execute("insert into kbc.player (username) values ('{}')".format(tempuser))
Related
i'm a bit of an amateur IT Professional who has been getting to grips with Python and Django. This query is just for Python and SQLite3.
So I have the following code, which is meant to take an input from the user, and then pass it to a function I have created.
from dbadd import inputdetails
import sqlite3
conn = sqlite3.connect('torndata.db')
c = conn.cursor()
print('Enter Name')
u_name = str(input())
print('Enter Age')
u_age = int(input())
print('Enter Gender')
u_gender = str(input())
inputdetails(u_name, u_age, u_gender)
conn.close()
And this is the function it is calling:
import sqlite3
conn = sqlite3 . connect ( 'torndata.db' )
cursor = conn.cursor ()
def inputdetails(u_name,u_age,u_gender):
cursor.execute("""
INSERT INTO userdata(name, age, gender)
VALUES (?,?,?)
""", (u_name, u_age, u_gender))
conn.commit()
I get no errors when it runs, but when I run the following, it shows no data has been moved to the table I have specified.
c.execute("SELECT * FROM userdata")
print(c.fetchall())
conn.commit()
conn.close()
The database is already created within SQLite3 and the table has been set up, I can query it directly.
Bad indent. The commit statement is not part of the function.
I have below sqlite query
SELECT EMP_CODE, FullName FROM EmpMaster
I have below code in python
I will then create CSV/xlsx file on the data extracted. Kindly provide python code for select statement.
You can execute SQL statements directly python,
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="mydatabase")
mycursor = mydb.cursor()
mycursor.execute("SELECT EMP_CODE, FullName FROM EmpMaster")
myresult = mycursor.fetchall()
for more on mysql check this link
I'm setting up a project by using python language to take feedback from customers by pressing the button, my question about the code to enter the data into the database?
import mysql.connector
connector = mysql.connector.connect(host="host", user="user", passwd="password", database="DB")
cnx = connector.cursor()
cnx.execute("INSERT INTO ... VALUES (%s)", ('data'))
# Or execute a query just as always
#cnx.execute("INSERT INTO ... VALUES (...)")
connector.commit()
# If "SELECT * FROM ..." use next line to get the data
#result = cnx.fetchall()
cnx.close()
connector.close()
In Python version 2.7.6
Pandas version 0.18.1
MySQL 5.7
import MySQLdb as dbapi
import sys
import csv
import os
import sys, getopt
import pandas as pd
df = pd.read_csv('test.csv')
rows = df.apply(tuple, 1).unique().tolist()
db=dbapi.connect(host=dbServer,user=dbUser,passwd=dbPass)
cur=db.cursor()
for (CLIENT_ID,PROPERTY_ID,YEAR) in rows:
INSERT_QUERY=("INSERT INTO {DATABASE}.TEST SELECT * FROM {DATABASE}_{CLIENT_ID}.TEST WHERE PROPERTY_ID = {PROPERTY_ID} AND YEAR = {YEAR};".format(
CLIENT_ID=CLIENT_ID,
PROPERTY_ID=PROPERTY_ID,
YEAR=YEAR,
DATABASE=DATABASE
))
print INSERT_QUERY
cur.execute(INSERT_QUERY)
db.query(INSERT_QUERY)
This will print out the query I am looking for, however, without successfully returning the results of INSERT INTO when I checked the results in MySQL
INSERT INTO test.TEST SELECT * FROM test_1.TEST WHERE PROPERTY_ID = 1 AND YEAR = 2015;
However, if I just copy and paste this MySQL query into MySQL GUI, it will execute without any problem. Could any guru enlighten?
I also tried the following
cur.execute(INSERT_QUERY, multi=True)
Returns an error
TypeError: execute() got an unexpected keyword argument 'multi'
The answer here is we need to use "from mysql.connector" and a db.commit(). Here is a good example
http://www.mysqltutorial.org/python-mysql-insert/
import MySQLdb as dbapi
import mysql.connector
import sys
import csv
import os
import sys, getopt
import pandas as pd
df = pd.read_csv('test.csv')
rows = df.apply(tuple, 1).unique().tolist()
db=dbapi.connect(host=dbServer,user=dbUser,passwd=dbPass)
cur=db.cursor()
conn = mysql.connector.connect(host=dbServer,user=dbUser,port=dbPort,password=dbPass)
cursor=conn.cursor()
for (CLIENT_ID,PROPERTY_ID,YEAR) in rows:
INSERT_QUERY=("INSERT INTO {DATABASE}.TEST SELECT * FROM {DATABASE}_{CLIENT_ID}.TEST WHERE PROPERTY_ID = {PROPERTY_ID} AND YEAR = {YEAR};".format(
CLIENT_ID=CLIENT_ID,
PROPERTY_ID=PROPERTY_ID,
YEAR=YEAR,
DATABASE=DATABASE
))
print INSERT_QUERY
cursor.execute(INSERT_QUERY)
conn.commit()
Only by having the commit, the database/ table changes will be accepted
I was using mysql-connector pool, trying to insert a new row into a table, and got the same problem. The version info: mysql-8, python3.7.
The solution is to add connection.commit at last even you didn't start transaction.
I want to display a specific column from sqlite3 on a python Tkinter combobox, but what's displayed instead is <sqlite3.Cursor object at 0x0000000003E73110>, I don't know what to do? I just started coding not a while ago.
I write the following:
from tkinter import *
from tkinter import ttk
import sqlite3
conn = sqlite3.connect('Library.db')
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS tablename (Name TEXT UNIQUE NOT NULL)")
combolist = c.execute("SELECT Name FROM tablename")
root = Tk()
ttk.Combobox(root, value = (combolist))
Calling execute on a cursor object won't return you the values. Instead you can iterate over the cursor, or call c.fetchall() to get all of the results back together.
sqlite3 also supports a shorthand where you can call conn.execute(...) and get back the results directly without using an explicit cursor at all, but that requires you to call execute on the connection rather than the cursor.
Also you may want to unpack the name field out of each row.
I think this code should work (though I haven't tested it):
conn = sqlite3.connect('Library.db')
with conn:
conn.execute("CREATE TABLE IF NOT EXISTS tablename (Name TEXT UNIQUE NOT NULL)")
... more code that actually inserts some data is assumed here ...
with conn:
combolist = [row["name"] for row in conn.execute("SELECT Name FROM tablename"))]