I created a program in python and mySQL that creates a database and imports data from text files and puts them in 4 different columns. The code works, but I want to change the code and create functions .
Can someone help me create a function that creates mySQL database? Here is the code that I have at the moment. Thanks in advance!
import MySQLdb
Ok, this is what I still have.
I get this error: TypeError: data_entry () takes no arguments (1 given)
And the data is also not inserted into the table from text files. Any help would be greatly appreciated!
import MySQLdb def connect_to_database(user, password): return MySQLdb.connect(host='localhost', user=user, passwd=password) def create_database(cursor): cursor.execute('CREATE DATABASE inb104') cursor.execute('USE inb104') cursor.execute('''CREATE TABLE popularity ( PersonNumber INT, Value VARCHAR(70), Category VARCHAR(25), PRIMARY KEY (PersonNumber, Value, Category) ) ''') def load_file(cursor, *files): """Load the files given in (filename, category) format.""" sql = '''LOAD DATA LOCAL INFILE '%s' INTO TABLE popularity FIELDS TERMINATED BY '\\t' LINES TERMINATED BY '\\n' (PersonNumber, Value, Category) SET Category='%s'") ''' for filename, category in files: cursor.execute(sql, (filename, category)) def data_entry(): """Connect to the DB server, create the DB and table and load the table with records """ db = connect_to_database('root', 'password') cursor = db.cursor() create_database(cursor) load_files(cursor,('tv.txt', 'TV'), ('actors.txt', 'Actors'), ('movies.txt', 'Movies')) db.commit() cursor.close() db.close()
python mysql
Kim
source share