I am trying to create a table in Python with MySQL, and then insert new values into the table!
The program works with no error message, but the table stays empty all the time. Here are my python scripts:
cursor = conn.cursor()
cursor.execute('DROP TABLE twitter')
cursor.execute("CREATE TABLE twitter (id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id CHAR, state CHAR(2), city CHAR, tweet CHAR, PRIMARY KEY (id))")
### after getting some data, then insert the data into the table:
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})'.format(tw_userid, tw_state, tw_city, tw_text))
cursor.close()
conn.commit()
conn.close()
But any time I try to select data from this table, I get an empty set.
I also tried without using format option, but still I get an empty set:
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})', (tw_userid, tw_state, tw_city, tw_text))
Any idea why the insert command doesn;t change the table at all?
You need to use a comma to separate parameters in python.
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})'.format(tw_userid, tw_state, tw_city, tw_text))
Should be:
data = (tw_userid, tw_state, tw_city, tw_text)
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})', data)
You can see the documentation for the python connector on the mysql documentation page.
Related
I test commands for sql by python. Generaly everything is okey, in this case, its doesn't work.
import sqlite3
conn = sqlite3.connect('Chinook_Sqlite.sqlite')
cursor = conn.cursor()
result = None
try:
cursor.executescript("""CREATE TABLE <New>;""")
result = cursor.fetchall()
except sqlite3.DatabaseError as err:
print("Error: ", err)
else:
conn.commit()
print(result)
conn.close()
Name writes with out <> and must include: name, type, default value after in ().
https://www.sqlite.org/lang_createtable.html - thanks #deceze
The "CREATE TABLE" command is used to create a new table in an SQLite
database. A CREATE TABLE command specifies the following attributes of
the new table:
he name of the new table.
The database in which the new table is created. Tables may be created in the main database, the temp database, or in any attached
database.
The name of each column in the table.
The declared type of each column in the table.
A default value or expression for each column in the table.
A default collation sequence to use with each column.
Optionally, a PRIMARY KEY for the table. Both single column and composite (multiple column) primary keys are supported.
A set of SQL constraints for each table. SQLite supports UNIQUE, NOT NULL, CHECK and FOREIGN KEY constraints.
Optionally, a generated column constraint.
Whether the table is a WITHOUT ROWID table.
cursor.executescript("""CREATE TABLE New ( AuthorId INT IDENTITY (1, 1) NOT NULL, AuthorFirstName NVARCHAR (20) NOT NULL, AuthorLastName NVARCHAR (20) NOT NULL, AuthorAge INT NOT NULL);""")
i run following codes in python3:
import sqlite3
conn = sqlite3.connect("data.db")
conn.execute("create table if not exists data(\
id int prinmary key,view int)")
conn.execute("insert into data (id,view) values (0,0)")
conn.execute("insert into data (id,view) values (1,'--')")
print(conn.execute("select * from data order by id").fetchall())
conn.commit()
conn.close()
and no error occured, "[(0, 0), (1, '--')]" was printed, why?
It is documented as a feature in SQLite documentation, is is even documented is its FAQ:
(3) SQLite lets me insert a string into a database column of type integer!
This is a feature, not a bug. SQLite uses dynamic typing. It does not enforce data type constraints. Data of any type can (usually) be inserted into any column...
From the sqlite page:
INSERT INTO table1 (
column1,
column2 ,..)
VALUES
(
value1,
value2 ,...);
After insert into data, you would need to tell it into which fields.
So I am trying to add a new entry into my mySQL Database.
The problem here is, that it increases the id, but does add the entry.
After a little bit of googling I found that a failed INSERT query also increases the AUTO_INCREMENTd value (id in my case).
The mySQL Table is created using
CREATE TABLE IF NOT EXISTS TS3_STAMM_1 (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(64) NOT NULL, ts3_uid VARCHAR(64) NOT NULL, points INT(8) UNSIGNED NOT NULL); which is called by the function qServer.execute(querystring) inside python's MySQLdb module.
Then I use qString = "INSERT INTO TS3_STAMM_1 (name, ts3_uid, points) VALUES ('{}', '{}', {})".format(name, uid, pnts) (the datatypes are correct, I at least quadrouplechecked) with the function qServer.exectue(qString) to insert a new entry into the database.
But it is incrementing the ID, but its not adding an entry. So my guess would be its a failed query, but why? How does it happen? How to fix it?
Simple SELECT querys work fine the same way, also adding data manually works fine. Only the python query fails.
Note: qServer is the connection to the server, and its defined with:
try:
qConn = MySQLdb.connect(host="...", user="...", passwd="...", db="...")
qServer = qConn.cursor()
except OperationalError:
print("Cannot connect to mySQL Database! Aborting...")
exit(1)
Use commit Luke.
>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)", ('Jane', ))
>>> qConn.commit()
Using str.format for creating SQL query is bad idea.
I'm trying to make a mysql table with python 2.7 using MySQLdb.
I've written a program to retrieve tweets based off of a search or "query" from twitter.
I want the tweets to be stored in a MySQL database for later retrieval by their query.
Things to know beforehand: the variable "tweets" is a list of strings. I want the table to have two parts, the query (what the person searched) and the tweets.
What is supposed to happen, is it should cycle through the list of tweets and insert them into the table. I keep getting Syntax errors and I'm not sure why.
Maybe there is a better way to do this than how I am currently trying to? Or maybe I'm just doing it wrong? All suggestions appreciated.
Thanks
#Does the MySQL stuff
db=MySQLdb.connect(host = 'localhost',user='root',passwd="swag",db="tweets")
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS TWEETS")
sql = """CREATE TABLE TWEETS (
QUERY CHAR(40) NOT NULL,
TWEET BLOB,
)"""
cursor.execute(sql)
#Inserts tweets into MySQLdb
for i in range(0,len(tweets)):
sql = "INSERT INTO TWEETS(QUERY, \
TWEET) \
VALUES ('%s', '%s')" % \
(query, tweets[i])
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
I am using MySQL-python interface 1.2.3 and MySQL server version 5.1.63.
Writing python script to create Table and insert data into the table. Its working Fine.
Now i am using MySQL server version 5.5.27 and executing same script to create table and insert data. i am able to create Tables but unable to insert data into the Table.
I am not able to get where i am doing wrong.
Could anyone help me how to overcome from this issue.
Thanks in Advance
When i was using MySQL server version 5.1.63 at that time i was not using db_connection.commit() to save the data into database. But without using also i was able to save data into MySQL database.
Example:
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
After this execution data will update into database.
But with 5.5.27 MySQL server version we need to use db_connection.commit() to save the data into database.
Example:
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()