I'm trying to use SQLite with python and I'm going over examples from the python website. One example is to build a shell for SQLite:
py
This is the beginning of the script
import sqlite3
con = sqlite3.connect(":memory:")
con.isolation_level = None
cur = con.cursor()
I'm loading the file from a text editor, and I'm confused by the error that I get when I import the file.
>>>import SQLoad
Traceback (most recent call last):
File"<stdin>", line 1, in <module>
File "SQLoad.py", line 1, in <module>
c = conn.cursor()
NameError: name 'conn' is not defined
I'm confused because 'conn' isn't being defined in what I'm uploading. Is it something that has to be defined?
Your first code block shows that the connection variable is named con.
The error message shows that you have written that variable as conn, and that this is in the first line of SQLoad.py, where the connection cannot have been opened yet.
Your first code block looks correct, but it is not what is actually stored in SQLoad.py.
Related
I'm trying to migrate my data from MongoDB to Mysql and my data has more than 1M records.
I've used Studio 3T for this but it limits the records to 1000 records (well we don't have the budget to buy the premium version). Hence, I'm trying to use python following this post: "http://www.youngdba.com/2017/03/migrating-mongodb-data-to-mysql-using.html".
Everything went smoothly until the last part which the python shell returns the error:
cursor1= db.cursor()
i=1
for abc in cursor:
uids=int(abc.get("uids"))
fnames=abc.get("first_name")
sql= "insert into client_test(uid,first_name) values"+'('+str(uids)+",'"+fnames+"')"
print ("Inserted"+str(i)+" record")
i+=1
Number_of_rows=cursor1.execute(sql)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in
for abc in cursor:
NameError: name 'cursor' is not defined
Why is the code not working? Am I missing something here?
Please help! Thank you in advance!
Your for loop should be:
for abc in cursor1:
There's no variable named cursor, only cursor1. You are missing the 1 from the variable name.
I am attempting to execute the following (move a column to be the first one)
import sqlite3
db = sqlite3.connect('adatabase.sqlite')
c = db.cursor()
c.execute('ALTER TABLE tab1 CHANGE COLUMN r r def FIRST')
Unfortunately I get this error
Traceback (most recent call last):
File "<input>", line 1, in <module>
OperationalError: near "CHANGE": syntax error
What could be? Thanks in advance
SQLite does not support a CHANGE COLUMN feature; if any.
Only the RENAME TABLE and ADD COLUMN variants of the ALTER TABLE
command are supported
See all missing features: SQL Features That SQLite Does Not Implement
I am trying to connect with db using the following code:
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="root", # your password
db="test101") # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * FROM test1")
# print all the first cell of all the rows
for row in cur.fetchall():
print row[0]
db.close()
However, I am getting the following error message on the console:
Traceback (most recent call last):
File "C:\Users\JRambo\workspace\DBConnection\src\DBConnection.py", line 6, in <module>
import MySQLdb
File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 19, in <module>
import _mysql
ImportError: DLL load failed: %1 is not a valid Win32 application.
I have followed the steps meticulously.
How do I connect to a MySQL Database in Python?
You might want to verify that you have the correct bit Python and correct bit MySQLdb. If you have 32 bit Python and 64 bit MySQLdb it won't work. I had a similar problem with the same Traceback error and when I installed the correct bit type of each application, bingo! Hope this helps!
I am trying to make an app similar to StumbleUpon using Python as a back end for a personal project . From the database I retrieve a website name and then I open that website with webbrowser.open("http://www.website.com"). Sounds pretty straight forward right but there is a problem. When I try to open the website with webbrowser.open("website.com") it returns the following error:
File "fetchall.py", line 18, in <module>
webbrowser.open(x)
File "/usr/lib/python2.6/webbrowser.py", line 61, in open
if browser.open(url, new, autoraise):
File "/usr/lib/python2.6/webbrowser.py", line 190, in open
for arg in self.args]
TypeError: expected a character buffer object
Here is my code:
import sqlite3
import webbrowser
conn = sqlite3.connect("websites.sqlite")
cur = conn.cursor()
cur.execute("SELECT WEBSITE FROM COLUMN")
x = cur.fetchmany(1)
webbrowser.open(x)
EDIT
Okay thanks for the reply, but now I'm receiving this: "Error showing URL: Error stating file '/home/user/(u'http:bbc.co.uk,)': No such file or directory".
What's going on ?
webbrowser.open is expecting a character buffer, but fetchmany returns a list. So webbrowser.open(x[0]) should do the trick.
I have a very weird problem with mysqldb (mysql module for python).
I have a file with queries for inserting records in tables. If I call the functions from the file, it works just fine; but when trying to call one of the functions from another file it throws me a
_mysql_exception.InterfaceError: (0, '')
I really don't get what I'm doing wrong here..
I call the function from buildDB.py :
import create
create.newFormat("HD", 0,0,0)
The function newFormat(..) is in create.py (imported) :
from Database import Database
db = Database()
def newFormat(name, width=0, height=0, fps=0):
format_query = "INSERT INTO Format (form_name, form_width, form_height, form_fps) VALUES ('"+name+"',"+str(width)+","+str(height)+","+str(fps)+");"
db.execute(format_query)
And the class Database is the following :
import MySQLdb
from MySQLdb.constants import FIELD_TYPE
class Database():
def __init__(self):
server = "localhost"
login = "seq"
password = "seqmanager"
database = "Sequence"
my_conv = { FIELD_TYPE.LONG: int }
self.conn = MySQLdb.connection(host=server, user=login, passwd=password, db=database, conv=my_conv)
# self.cursor = self.conn.cursor()
def close(self):
self.conn.close()
def execute(self, query):
self.conn.query(query)
(I put only relevant code)
Traceback :
Z:\sequenceManager\mysql>python buildDB.py
D:\ProgramFiles\Python26\lib\site-packages\MySQLdb\__init__.py:34: DeprecationWa
rning: the sets module is deprecated
from sets import ImmutableSet
INSERT INTO Format (form_name, form_width, form_height, form_fps) VALUES ('HD',0
,0,0);
Traceback (most recent call last):
File "buildDB.py", line 182, in <module>
create.newFormat("HD")
File "Z:\sequenceManager\mysql\create.py", line 52, in newFormat
db.execute(format_query)
File "Z:\sequenceManager\mysql\Database.py", line 19, in execute
self.conn.query(query)
_mysql_exceptions.InterfaceError: (0, '')
The warning has never been a problem before so I don't think it's related.
I got this error when I was trying to use a closed connection.
Problem resolved.. I was initializing the database twice.. Sorry if you lost your time reading this !
I couldn't get your setup to work. I gives me the same error all the time. However the way you connect to and make queries to the db with the query seems to be "non-standard".
I had better luck with this setup:
conn = MySQLdb.Connection(user="user", passwd="******",
db="somedb", host="localhost")
cur = conn.cursor()
cur.execute("insert into Format values (%s,%s,%s,%s);", ("hd",0,0,0))
This way you can take advantage of the db modules input escaping which is a must to mitigate sql injection attacks.