How to create table dynamically in python mysql.connector? - python

I got an error in the 5th line in my code below at '"+uname+"'.
How can I create a table at runtime?
Here is my code :
name = en1.get()
uname = en2.get()
password = en3.get()
sql = "insert into register values ('" + name + "','" + uname + "','" + password + "')"
CreateTable = "CREATE TABLE '"+uname+"'(no INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255),amount INT,date DATE,mode VARCHAR(255))"
try:
cur.execute(sql)
cur1.execute(CreateTable)
con.commit()
con1.commit()
messagebox.showinfo("Success", "Your data is registered successfully!")
except:
messagebox.showinfo("Error inserting", "Please change your username and try.")

In the statements with get(), if you get None as a return value then the below statements will fail
name = en1.get() #-- None
sql = "insert into register values ('" + name + "','" + uname + "','" + password + "')"
CreateTable = "CREATE TABLE '"+uname+"'(no INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255),amount INT,date DATE,mode VARCHAR(255))"
Try this instead so that if any of the values is None, then below output will be obtained
without causing the error but still the sql query needs to be handled
sql = "insert into register values ('{}','{}','{}')".format(name, uname, password)
CreateTable = "CREATE TABLE '{}'(no INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255),amount INT,date DATE,mode VARCHAR(255))".format(name)
print("sql is ", sql)
print("sql is ", CreateTable)
# Output
sql is insert into register values ('None','None','None')
sql is CREATE TABLE 'None'(no INT AUTO_INCREMENT PRIMARY KEY,title VAR
CHAR(255),amount INT,date DATE,mode VARCHAR(255))

Related

sqlite3.OperationalError: table users has no column named username

Hello I cant figure out the solution for that problem. I searched on google but got no answer.
I'm new to db. so maybe its a dumb question :).
class Users:
def __init__(self, tablename="users", userId="userId", password="password", username="username"):
self.__tablename = tablename
self.__userId = userId
self.__password = password
self.__username = username
conn = sqlite3.connect('test.db')
print("open database successfully")
str = "CREATE TABLE IF NOT EXISTS " + tablename + "(" + self.__userId + " " + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
str += " " + self.__password + "TEXT NOT NULL ,"
str += " " + self.__username + "TEXT NOT NULL )"
conn.execute(str)
print("Table created successfully")
conn.commit()
conn.close()
def insert_user(self, username, password):
conn = sqlite3.connect('test.db')
str_insert = "INSERT INTO " + self.__tablename + " (" + self.__username +"," + self.__password + ") VALUES (" + "'" +username + "'" + "," + "'" +password +"'" +");"
print(str_insert)
conn.execute(str_insert)
conn.commit()
conn.close()
print("Record created successfully")
u = Users()
u.insert_user("yonatan#gmail.com", "123456")
Problem is here :
str = "CREATE TABLE IF NOT EXISTS " + tablename + "(" + self.__userId + " " + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
str += " " + self.__password + "TEXT NOT NULL ,"
str += " " + self.__username + "TEXT NOT NULL )"
Indeed, concatenate "username" and "TEXT NOT NULL" will give "usernameTEXT NOT NULL", without space between "username" and "TEXT"
You can see this if you execute the following query :
conn.execute("SELECT * from sqlite_master").fetchall()
This gives you :
[
('table', 'users', 'users', 2, 'CREATE TABLE users(userId INTEGER PRIMARY KEY AUTOINCREMENT , passwordTEXT NOT NULL , usernameTEXT NOT NULL )'),
('table', 'sqlite_sequence', 'sqlite_sequence', 3, 'CREATE TABLE sqlite_sequence(name,seq)')
]
Which is clearly a mess.
When you work with sqlite3, a good practice is to use the following syntax, which will avoid you a lot of space mistakes :
conn.execute(
f"CREATE TABLE IF NOT EXISTS {tablename}"
f"({self.__userId} INTEGER PRIMARY KEY AUTOINCREMENT,"
f"{self.__password} TEXT NOT NULL, {self.__username} TEXT NOT NULL)"
)

python unable to parse table name correctly in sql query

I am newbie to snowflake. I am trying to fetch ddl s of all tables in my db using python script.
import snowflake.connector
import sys
# Gets the version
cnx = snowflake.connector.connect(
user='username',
password='password',
account='account',
database='db',
schema='schema',
warehouse='warehouse',
role='role'
)
cnx.cursor().execute("USE warehouse warehouseName")
cnx.cursor().execute("USE database dbName")
cnx = cnx.cursor()
dbSchema='schema name'
sql_select_objects = "select TABLE_NAME,TABLE_SCHEMA,TABLE_TYPE from INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='" + dbSchema + "';"
print(sql_select_objects)
try:
cnx.execute(sql_select_objects)
print('Query ID=' + cnx.sfqid)
rows = cnx.fetchall()
print("rows count:", len(rows))
for row in rows:
#print(row[0])
file = open(row[0] + ".sql","w")
rw='"' + row[0] + '"'
print(rw)
sql_ddl_object = "SELECT GET_DDL('TABLE', '" + row[0] + "')"
print(sql_ddl_object)
cnx.execute(sql_ddl_object)
print('SQL2 sfqid=' + cnx.sfqid)
row_ddl_table = cnx.fetchall()
#print(row_ddl_table[0][0])
file.write(str(row_ddl_table[0][0]))
file.write("\n")
finally:
cnx.close()
When I execute above script i get error:
snowflake.connector.errors.ProgrammingError: 002003 (02000): SQL compilation error:
Table 'SNOWFLAKE_TEST' does not exist or not authorized.
in line "SELECT GET_DDL('TABLE', '" + row[0] + "')", i believe python is not parsing value of row[0] correctly. Can you please suggest me where the error is?
Please use both schema and table name as you may have the table SNOWFLAKE_TEST in a different schema:
"SELECT GET_DDL('TABLE', '" + row[1] + "." + row[0] + "')"
I would also surround the table name and schema names in double quotes because maybe your schema or table is created with a case-sensitive name:
"SELECT GET_DDL('TABLE', '\"" + row[1] + "\".\"" + row[0] + "\"')"
Most likely the issue is not with the table name but the role that you are using in the code. The role most likely does not have access to the DB and it's table hence the error message is seen.

How to get columns from a query in python?

I have that query in a python program:
And i should create a multidimensional array (if it possible) or four arrays from this query for every column from the query.
Can you suggest an elegant way to solve it?
conn = #connection to the server
cursor=conn.cursor()
query = (" select id, name, phone, city from guest")
cursor.execute(query)
results = cursor.fetchall
for i in results:
print i
cursor.close()
conn.close()
Not elegant but it may assist to unravel the mysterious Python Connector Cursor Class and transfers the list of tuples (see Copperfield comment) with the data from the query, into a list (phoneList) of dictionaries (entries) with details of each entry in the database, that might be easier to work with in your python script:
# ref: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor.html
import mysql.connector
db = 'test'
table = 'phonebook'
phoneList = []
drop_table = ("DROP TABLE IF EXISTS {};").format(table)
# By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
# To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
# ALTER TABLE phonebook AUTO_INCREMENT=100;
create_table = ("CREATE TABLE {} ("
"id int NOT NULL AUTO_INCREMENT,"
"name varchar(30) NOT NULL,"
"phone varchar(30) NOT NULL,"
"city varchar(30) NOT NULL,"
"PRIMARY KEY (id))"
" ENGINE=InnoDB DEFAULT CHARSET=latin1;").format(table)
Names = {'Bill':{'phone':'55123123','city':'Melbourne'},
'Mary':{'phone':'77111123','city':'Sydney'},
'Sue':{'phone':'55888123','city':'Melbourne'},
'Harry':{'phone':'77777123','city':'Sydney'},
'Fred':{'phone':'88123444','city':'Yongala'},
'Peter':{'phone':'55999123','city':'Melbourne'}}
cnx = mysql.connector.connect(user='mysqluser', password='xxxx',host='127.0.0.1',database=db)
cursor = cnx.cursor(dictionary=True) # key to using **row format
cursor.execute(drop_table)
cursor.execute(create_table)
# populate db
for name,detail in dict.items(Names):
sql = ("INSERT INTO {} (name,phone,city) VALUES ('{}','{}','{}')".format(table,name,detail['phone'],detail['city']))
cursor.execute(sql)
sql = ("SELECT id,name,phone,city FROM {}".format(table))
cursor.execute(sql)
for row in cursor:
print("{id} {name} {phone} {city}".format(**row))
phoneList.append(row)
print phoneList[0]['name'],phoneList[0]['city']
print phoneList[3]['name'],phoneList[3]['phone']
for entries in phoneList: # list of dictionaries
print entries['name'],entries
for entries in phoneList:
for k,v in dict.items(entries):
print k,v
print "\n"
cnx.close()

Python MySQLdb: creating database and filling table

I have written a small script to create a MySQL database, create a table (previously erase it if already exists), and insert many entries. When I execute my script, it works creating the database and table, but does not write any entry to the table:
from warnings import filterwarnings
import MySQLdb as db
filterwarnings('ignore', category = db.Warning)
try:
db_name = 'chom'
con = db.connect(user='user', passwd='pass')
cur = con.cursor()
# Create new database
cur.execute('CREATE DATABASE IF NOT EXISTS ' + db_name + ';')
# Create PARAMETERS table
cur.execute('DROP TABLE IF EXISTS ' + db_name + '.PARAMETERS;')
query = ('CREATE TABLE ' + db_name + '.PARAMETERS ('
'idPARAMETERS INT(10) NOT NULL AUTO_INCREMENT, '
'Param_name VARCHAR(30) NULL DEFAULT NULL, '
'Param_value VARCHAR(255) NULL DEFAULT NULL, '
'Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP '
'ON UPDATE CURRENT_TIMESTAMP, '
'User_id VARCHAR(20) NULL DEFAULT NULL, '
'PRIMARY KEY (idPARAMETERS) );'
)
cur.execute(query)
# Insert entries
parameters = ['param1', 'param2', 'param3',
'param4']
for i, param_name in enumerate(parameters, start=1):
cur.execute('INSERT INTO ' + db_name + '.PARAMETERS '
'(idPARAMETERS, Param_name, Param_value, User_id) '
'VALUES (' + str(i) + ', %s, %s, %s);',
(param_name, '', 'user2#localhost'))
cur.close()
con.commit()
except Exception, e:
print 'Error. Last query: ' + str(cur._last_executed)
print e
print 'DB installation script finished'
I can't see where the problem is. Any idea?
The code worked correctly, it was mysql-workbench fault, which was not showing the correct database content (while mysql console client did).

(python) Databases, incorrect syntax error

I'm completely new to databases, and have put something simple together using the helpful guide that can be located at http://halfcooked.com/presentations/osdc2006/python_databases.html , However it's returning an error that I don't understand
try:
from sqlite3 import dbapi2 as sqlite
except ImportError:
from pysqlite2 import dbapi2 as sqlite
db_connection = sqlite.connect('program.db')
db_curs = db_connection.cursor()
def create_customer(cID, fname, sname, dob):
db_curs.execute("CREATE TABLE " + cID + " ( id INTEGER PRIMARY KEY, first_name VARCHAR(20),last_name VARCHAR(30), date_of_birth DATE)")
db_curs.execute("INSERT INTO " + cID + " (first_name, last_name, date_of_birth) VALUES (fname, sname, dob)")
db_connection.commit()
db_curs.execute("SELECT * FROM " + cID )
create_customer("1", "John", "Farnham", "12/08/95")
create_customer("1", "Indianna", "Jones", "05/05/95")
print db_curs.fetchall()
the error I am receiving is as follows:
Traceback (most recent call last):
File "C:\Users\fin0005\Documents\loyalty.py", line 17, in <module>
create_customer("1", "John", "Farnham", "12/08/95")
File "C:\Users\fin0005\Documents\loyalty.py", line 12, in create_customer
db_curs.execute("CREATE TABLE " + cID + " ( id INTEGER PRIMARY KEY, first_name VARCHAR(20),last_name VARCHAR(30), date_of_birth DATE)")
OperationalError: near "1": syntax error
Add backticks around your table name, so that it doesn't think it's creating an integer as a table name
def create_customer(cID, fname, sname, dob):
db_curs.execute("CREATE TABLE `" + cID + "` ( id INTEGER PRIMARY KEY, first_name VARCHAR(20),last_name VARCHAR(30), date_of_birth DATE)")
db_curs.execute("INSERT INTO `" + cID + "` (first_name, last_name, date_of_birth) VALUES (fname, sname, dob)")
db_connection.commit()
db_curs.execute("SELECT * FROM `" + cID + "`")
# In SQL terms, the following blows up
# create table 2 (id int(10) PRIMARY KEY); Due to the 2 being an integer
# create table `2` (id int(10) PRIMARY KEY); Works, due to the 2 being properly identified with backticks :)
# Here's some code as requested in the comment, everything below this point is a self contained example, please do not copy the function above
def initiate_customer_table(table_name):
db_curs.execute("CREATE TABLE IF NOT EXISTS `" + table_name + "` ( id INTEGER PRIMARY KEY, first_name VARCHAR(20),last_name VARCHAR(30), date_of_birth DATE)")
db_connection.commit()
def create_customer(table_name, fname, sname, dob):
db_curs.execute("INSERT INTO `" + table_name + "` (first_name, last_name, date_of_birth) VALUES (%s, %s, %s)", [fname, sname, dob])
db_connection.commit()
# Fetches the user just created
db_curs.execute("SELECT * FROM `" + table_name + "` WHERE id = %s", [db_curs.insert_id()])
# Returns the user
return db_curs.fetchone()
desired_table_name = 'customers'
initiate_customer_table(desired_table_name)
customer_1 = create_customer(desired_table_name, "Bryan", "Moyles", "1800-01-01")
customer_2 = create_customer(desired_table_name, "Awesome", "Guy", "1800-01-01")
I will also suggest that you go a step further, if you plan on using this code in production, to ensure that all fields are escaped properly for mysql.

Categories