I want to create a new mysqldb table for each unique user, but i'm getting errors:
1.'bytes' object has no attribute 'encode'
2.Can't convert 'bytes' object to str implicitly
3.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Text'(
id int(11) NOT NULL AUTO_INCREMENT,
UserName text NOT NULL' at line 1
c.execute("CREATE TABLE IF NOT EXISTS {table_name}".format(table_name=belekas), (belekas) + """(
`id` int(11) NOT NULL AUTO_INCREMENT,
`UserName` text NOT NULL,
`Data` date NOT NULL,
`Laikas` time NOT NULL,
`KeyStrokes` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8""")
con.commit()
c.execute("INSERT INTO {table_name} VALUES (id, %s, Data, Laikas, %s)".format(table_name=belekas),
(belekas, vartotojas, tekstas))
con.commit()
I tried using:
c.execute("CREATE TABLE IF NOT EXISTS" + vartotojas + """(
and this:
c.execute("CREATE TABLE IF NOT EXISTS" + repr(vartotojas.decode('utf-8')) + """(
and this:
c.execute("CREATE TABLE IF NOT EXISTS {this_table}".format(this_table=vartotojas), (vartotojas.encode("utf-8")) + """(
Can someone suggest solution for this problem?
Related
Im receiving an error where I am using an incorrect integer value for userID_fk and target. The error comes up for values which have an integer as their data type and if its changed to text or varchar it will state a site has been created and the siteID will increase but no other data will be included. I want the user to input their username so its matched with its userID and inserted into userID_fk through python with Tkinter.
Below is the structure for my users and sites table
users:
CREATE TABLE `users` (
`userID` int(255) NOT NULL AUTO_INCREMENT,
`userName` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
`userPassword` varchar(225) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
`Name` varchar(255) NOT NULL,
`phoneNum` text NOT NULL,
`email` varchar(230) NOT NULL,
`region` text NOT NULL,
`accessLevel` int(10) NOT NULL,
PRIMARY KEY (`userID`)
) ENGINE=InnoDB AUTO_INCREMENT=10002 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT
sites:
CREATE TABLE `sites` (
`siteID` int(225) NOT NULL AUTO_INCREMENT,
`siteName` text CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
`userID_fk` int(255) NOT NULL,
`region` text NOT NULL,
`risklevel` text NOT NULL,
`siteType` text NOT NULL,
`target` int(225) NOT NULL,
PRIMARY KEY (`siteID`),
KEY `userID_fk` (`userID_fk`),
CONSTRAINT `sites_ibfk_1` FOREIGN KEY (`userID_fk`) REFERENCES `users` (`userID`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT
Python code to insert a site into the sites table:
def register_site():
sitename_info = sitename2.get()
username2_info = username2.get()
region_info = region.get()
risklevel_info = risklevel.get()
sitetype_info = sitetype.get()
targetpercent_info = targetpercent.get()
# Sql code for writing the data that was written in the regsitering page.
cursor = cnn.cursor()
sitequery = "INSERT INTO `sites`(`siteID`, `siteName`, `userID_fk`, `region`, `risklevel`, `siteType`, `target`) VALUES (NULL,%s,%s,%s,%s,%s,%s)"
sitequery_vals = (sitename_info, username2_info, region_info, risklevel_info, sitetype_info, targetpercent_info)
cursor.execute(sitequery, sitequery_vals)
cnn.commit()
cursor.close()
cnn.close()
# removes the values in the entrys once the user selects that the registration was successful
sitename2_entry.delete(0, END)
region_entry.delete(0, END)
risklevel_entry.delete(0, END)
sitetype_entry.delete(0, END)
targetpercent_entry.delete(0, END)
Label(screen10, text = "Site Created", fg = "green", font = ("calibri", 11)).pack()
If username2_info is the userName, you need to get the userID from the users table:
sitequery = ("INSERT INTO `sites` (`siteName`, `userID_fk`, `region`, `risklevel`, `siteType`, `target`) "
"SELECT %s, `userID`, %s, %s, %s, %s FROM `users` WHERE `userName` = %s")
sitequery_vals = (sitename_info, region_info, risklevel_info, sitetype_info, targetpercent_info, username2_info)
cursor.execute(sitequery, sitequery_vals)
cnn.commit()
I've got a CSV excel file, which one I want to convert into mysqldb.
It is working very fine, but in every cell in the MYSQLdb there are unnecessary quotation marks, like this: "".
When the cell is empty I see this: ""
When the cell is not empty is see this: "somethingdata"
I can't understand, why put these quotation marks when in the csv file there are none.
Here my code, I think it is correct too.
connection = MySQLdb.connect(host='localhost',
user='root',
passwd='1234',
db='database')
cursor = connection.cursor()
query = """
CREATE TABLE `test` (
`Megnevezes` varchar(100) DEFAULT NULL,
`2015` varchar(100) DEFAULT NULL,
`2014` varchar(100) DEFAULT NULL,
`2013` varchar(100) DEFAULT NULL,
`2012` varchar(100) DEFAULT NULL,
`2011` varchar(100) DEFAULT NULL,
`ID` int(10) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8"""
cursor.execute(query)
connection.commit()
cursor.close()
connection = MySQLdb.connect(host='localhost',
user='root',
passwd='1234',
db='database')
cursor = connection.cursor()
query = """ load data local infile 'C:/Python27/output.csv'
into table test
character set latin1
fields terminated by ';'
lines terminated by '\n'
ignore 1 lines;
"""
cursor.execute(query)
connection.commit()
cursor.close()
Any ideas how can I fix this issue?
https://dev.mysql.com/doc/refman/5.7/en/load-data.html
Use the: ENCLOSED BY 'char' where char will be "
I´m using python psycopg2 library to create a table in a postgres database:
self.conn=pg.connect(host='localhost',user='eba',password='****',database='eba')
cur=self.conn.cursor()
cur.execute(sql)
cur.close()
sql='''CREATE TABLE public.tempimport (
id integer NOT NULL DEFAULT nextval('tempimport_id_seq'::regclass),
tablename character varying(32) COLLATE pg_catalog."default",
index_ character varying(32) COLLATE pg_catalog."default",
CONSTRAINT tempimport_pkey PRIMARY KEY (id)
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public.tempimport
OWNER to eba;'''
cur=self.conn.cursor()
cur.execute(sql)
cur.close()
After, if I run:
cur=self.conn.cursor()
cur.execute("SELECT count(*) FROM pg_catalog.pg_tables where tablename = 'tempimport'")
x=cur.fetchall()
print x
I get 1 as the answer, that is, the table exists.
However, if I log in the same database/user/pwd using pgAdmin and run the same SELECT COUNT(*)... sentence there I get 0 as the answer.
Where is the table I created by code?
How can I find to find where it is?
Try using information_schema:
SELECT *
FROM information_schema.tables
WHERE table_name = 'tempimport'
I am coding with mysql-python.
To add a new record into database, I use the following piece of code:
# Open database connection
db = MySQLdb.connect("localhost","root","admin","majoranalysis" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "INSERT INTO
# insert a record
jobdetail(title,date_accessed,description,requirement,url) \
VALUES(%(title)s,%(data_accessed)s,%(description)s,%(requirement)s,%(url)s)"
dt = ('data analysist',date(2015,4,16),'description','requirement',joblistlink[0])
cursor.execute(sql,dt)
The problem is not to declare str, but the error occurs likely:
Traceback (most recent call last):
File "./re-ex.py", line 81, in <module>
dt = ('data analysist',date(2015,4,16),'description','requirement',joblistlink[0])
TypeError: 'str' object is not callable
The sql command to create the table is:
CREATE TABLE IF NOT EXISTS `jobdetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
`date_accessed` date NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
`requirement` text COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
Do you know where is the bug?
Because you use the %(key)s as a place holder in your sql str.So that means you should use a dictionary to give the data to the sql.
Eg.
give tuple to %s like :print "%s:%s" % ('key', 'val')
give dict to %(key)s like print '%(k1)s:%(v1)s' % {'k1':'key', 'v1':'val'}
In case you still dont know how to fix your problem.Change to
dt={'title':'data analysist',
'data_accessed':date(2015,4,16),
'description':'description',
'requirement':'requirement',
'url':joblistlink[0]}
I am importing a csv file containing a parent/child (category-subcategory) hierarchy to MySQL, using Python's MySQLdb module. Here is an example csv file:
vendor,category,subcategory,product_name,product_model,product_price
First vendor,category1,subcategory1,product1,model1,100
First vendor,category1,subcategory2,product2,model2,110
First vendor,category2,subcategory3,product3,model3,130
First vendor,category2,subcategory4,product5,model7,190
In MySQL I want to use a category table with a hierarchical structure, like this:
CREATE TABLE IF NOT EXISTS `category` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL DEFAULT '0',
`status` tinyint(1) NOT NULL,
PRIMARY KEY (`category_id`),
KEY `parent_id` (`parent_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
My question is: How do I determine the parent_id in this table?
Here is the Python script I have so far:
import MySQLdb
import csv
con = MySQLdb.connect('localhost', 'root', '', 'testdb', use_unicode=True, charset='utf8')
with con:
cur = con.cursor()
csv_data = csv.reader(file('test.csv'))
csv_data.next()
for row in csv_data:
cur.execute("SELECT manufacturer_id FROM manufacturer WHERE name=%s", [row[0]],)
res = cur.fetchall()
if res:
vendor_id = res[0][0]
else:
cur.execute("INSERT INTO manufacturer (name) VALUES (%s)", (row[0],))
vendor_id = cur.lastrowid
cur.execute("SELECT category_id FROM category_description WHERE name=%s", [row[2]])
res = cur.fetchall()
if res:
category_id = res[0][0]
else:
# What parent_id should be inserted here?
cur.execute("INSERT INTO category (`status`, `parent_id`) VALUES (%s,%s)", (1,))
category_id = cur.lastrowid
cur.execute("INSERT INTO category_description (category_id, name) VALUES (%s,%s)", (category_id,row[2],))
cur.execute("INSERT INTO product (model, manufacturer_id, price,) VALUES (%s, %s, %s)", (row[4], `vendor_id`, row[8],))
product_id = cur.lastrowid
cur.execute("INSERT INTO product_to_category (product_id, category_id) VALUES (%s, %s)", (product_id, category_id,))
cur.commit()
Here are the definitions of the other tables used in my example:
CREATE TABLE IF NOT EXISTS `manufacturer` (
`manufacturer_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
PRIMARY KEY (`manufacturer_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE IF NOT EXISTS `category_description` (
`category_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`category_id`,`language_id`),
KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE IF NOT EXISTS `product` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`model` varchar(64) NOT NULL,
`manufacturer_id` int(11) NOT NULL,
`price` decimal(15,4) NOT NULL DEFAULT '0.0000',
PRIMARY KEY (`product_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE IF NOT EXISTS `product_to_category` (
`product_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
PRIMARY KEY (`product_id`,`category_id`),
KEY `category_id` (`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
In a hierarchical table structure, any member at the top of its hierarchy has no parents. I would probably show this with a NULL parent ID but based on the way you've defined your category table, it looks like you want to show this by giving the value 0 for the parent ID.
Since you have fixed-depth hierarchies with only two levels (category and subcategory), the task is relatively simple. For each row of the CSV data, you need to:
Check whether the parent (row[1]) is in the table; if not, insert it with a parent ID of 0.
Get the category_id of the parent from step 1.
Check whether the child (row[2]) is in the table; if not, insert it with a parent ID equal to the category_id from step 2.
In your example code, you never access the parent (row[1]); you need to insert this into the table for it to have an ID that the child can refer to. If you've already inserted the parents before this point, you should probably still check to make sure it's there.
You have some other problems here:
The PK of your category_description table is defined on a column that you forgot to define in the table (language_id).
You should really be using InnoDB in this physical model so that you can enforce foreign key constraints in category_description, product and product_to_category.
In your example, cur.commit() is going to throw an exception – that's a method of the Connection object in MySQLdb. Of course, COMMIT isn't implemented for MyISAM tables anyway, so you could also avoid the exception by removing the line entirely.
Referencing row[8] is also going to throw an exception, according to the CSV data you've shown us. (This is a good example of why you should test your MCVE to make sure it works!)
If you do switch to InnoDB – and you probably should – you can use with con as cur: to get a cursor that commits itself when you exit the with block. This saves a couple lines of code and lets you manage transactions without micromanaging the connection object.