I am trying to setup a python script to get some data and store it into a SQLite database. However when I am running the script a .fuse_hidden file is created.
On windows no .fuse_hidden file is observed but on ubuntu it generates at each call. The .fuse_hidden file seems to contain some form of sql query with input and tables.
I can delete the files without error during runtime but they are not deleted automatically. I make sure to end my connection to the db when I am finished with the query.
lsof give no information.
I am out of ideas on what to try next to get the files removed automatically. Any suggestions?
Testing
In order to confirm that it is nothing wrong with the code I made a simple script
(Assume there is an empty error.db)
import sqlite3
conn = sqlite3.connect("error.db")
cur = conn.cursor()
create_query = """
CREATE TABLE Errors (
name TEXT
);"""
try:
cur.execute(create_query)
except:
pass
cur.execute("INSERT INTO Errors (name) VALUES(?)", ["Test2"])
conn.commit()
cur.close()
conn.close()
Im trying read data from a smartmeter that has FTDI chip. Wrote a simple Python serial program to pass the commands to meter and the meter replies back. the data from meter is then converted to float and stored in dictionary.
now i want to store the dictionary to DB, here is the code to put data in the table.
import psycopg2
conn = psycopg2.connect(database="smartmeter", user="postgres", password="12345", host="localhost", port="5432")
cur = conn.cursor()
cur.execute('''CREATE TABLE metertable (ID SERIAL PRIMARY KEY NOT NULL,meter TEXT NOT NULL,temperature TEXT NOT NULL,freq TEXT NOT NULL,penergy TEXT NOT NULL,qenergy TEXT NOT NULL,senergy TEXT NOT NULL,cospi TEXT NOT NULL,irms TEXT NOT NULL,ppower TEXT NOT NULL,qpower TEXT NOT NULL,spower TEXT NOT NULL);''')
while 1:
data=dict[]
data={
'time':timestamp,
'meter':m0_data,
'temperature':m1_data,
'freq':m2_data,
'penergy':m3_data,
'qenergy':m6_data,
'senergy':m7_data,
'cospi':m11_data,
'irms':m15_data,
'vrms':m16_data,
'ppower':realpower,
'qpower':reactivepower,
'spower':apparentpower
}
cur.executemany ("""INSERT INTO metertable(time,meter,temperature,freq,penergy,qenergy,senergy,cospi,irms,vrms,ppower,qpower,spower) VALUES (%(time)s, %(meter)s), %(temperature)s), %(freq)s), %(penergy)s), %(qenergy)s), %(senergy)s), %(cospi)s), %(irms)s), %(vrms)s), %(ppower)s) %(qpower)s) %(spower)s)""", data)
I get an error like this
Traceback (most recent call last):
File "metercmd.py", line 97, in <module>
cur.executemany("""INSERT INTO metertable(time,meter,temperature,freq,penergy,qenergy,senergy,cospi,irms,vrms,ppower,qpower,spower) VALUES (%(time)s, %(meter)s), %(temperature)s), %(freq)s), %(penergy)s), %(qenergy)s), %(senergy)s), %(cospi)s), %(irms)s), %(vrms)s), %(ppower)s) %(qpower)s) %(spower)s)""", data)
TypeError: string indices must be integers, not str
Am I going on the right direction to enter data to the DB? Please suggest some best methods.
Error says: Some of fields you try to push into database are string fields but you push integer values.
Make sure that your data values matches your database table fields.
You have extra closing parenthesis and missing commas:
cur.executemany ("""
INSERT INTO metertable(
time,meter,temperature,freq,penergy,qenergy,senergy,cospi,irms,vrms,ppower,qpower,spower
) VALUES (
%(time)s, %(meter)s, %(temperature)s, %(freq)s, %(penergy)s, %(qenergy)s, %(senergy)s,
%(cospi)s, %(irms)s, %(vrms)s, %(ppower)s, %(qpower)s, %(spower)s
)
""", data)
Thanks for the help . The error was with the executemany. i used type(variable) to get the variable types and changed in those table I changed that to cur.execute. But when I run the code. I see no data saving in my database.
here is the code
import serial
import psycopg2
port=serial.Serial("/dev/ttyUSB0",baudrate=9600,timeout=.1)
conn =psycopg2.connect(database="smartmeternode",user="postgres",password="amma",host="localhost",port="5432")
cur=conn.cursor
data2=dict()
while 1:
port.write('m0\r')
meter=port.read()
port.write('m2\r')
temp=port.read()
ph=meter*temp
time=timestamp
data={'meter':meter,'temp':temp,'ph':ph,'time':time}
cur.execute("INSERT INTO METERDATATEST(meter,temp,ph,time) VALUES(%(meter)s,%(temp)s,%(ph)s,%(time)s;",data)
cur.commit
cur.close
conn.close
the program will run for ínfinite time and i stop the program using ctrl+Z. when I check the database its still empty. what am i missing? I want the data to be stored in the PSQL database as soon as it is read from my smartmeter
psql smartmeternode -U postgres
smartmeternode=# SELECT * FROM meterdatatest;
id | meter | temp | ph | time
----+-------+------+----+------
(0 rows)
I am new at SQLite in Python and I am trying to create a database connection.
I have the following as a datbase location:
E:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\master.mdf (i think)
The database is called FTHeader. However, when I try it i get an error saying unable to open database file
any help would be greatly appreciated.
Pick your poison from here and import the module as db and the following should sort you, cribbing from PEP 249:
import adodbapi as db
import adodbapi.ado_consts as db.consts
Cfg={‘server’:’192.168.29.86\\eclexpress’,‘password’:‘xxxx’,‘db’:‘pscitemp’}
constr = r”Provider=SQLOLEDB.1; Initial Catalog=%s; Data Source=%s; user ID=%s; Password=%s; “ \
% (Cfg['db'], Cfg['server'], ‘sa’, Cfg['password'])
conn=db.connect(constr)
You should now be connected to your database after replacing the Cfg dictionary to match your installation.
I have created a database when completing a controlled assesment, here is the code that I have used:
import sqlite3
new_db = sqlite3.connect ('R:\\subjects\\Computing & ICT\\Student Area\\Y11\\Emilyc\\results1.db')
c=new_db.cursor()
c.execute('''CREATE TABLE results1
(
results1_name text,
results1_class number,
quiz_score number)
''')
#Class 1
c.execute('''INSERT INTO results1
VALUES ('John Watson','1','5')''')
I'm trying to insert some data into a local MySQL database by using MySQL Connector/Python -- apparently the only way to integrate MySQL into Python 3 without breaking out the C Compiler.
I tried all the examples that come with the package; Those who execute can enter data just fine. Unfortunately my attempts to write anything into my tables fail.
Here is my code:
import mysql.connector
def main(config):
db = mysql.connector.Connect(**config)
cursor = db.cursor()
stmt_drop = "DROP TABLE IF EXISTS urls"
cursor.execute(stmt_drop)
stmt_create = """
CREATE TABLE urls (
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
str VARCHAR(50) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) CHARACTER SET 'utf8'"""
cursor.execute(stmt_create)
cursor.execute ("""
INSERT INTO urls (str)
VALUES
('reptile'),
('amphibian'),
('fish'),
('mammal')
""")
print("Number of rows inserted: %d" % cursor.rowcount)
db.close()
if __name__ == '__main__':
import config
config = config.Config.dbinfo().copy()
main(config)
OUTPUT:
Number of rows inserted: 4
I orientate my code strictly on what was given to me in the examples and can't, for the life of mine, figure out what the problem is. What am I doing wrong here?
Fetching table data with the script works just fine so I am not worried about the configuration files. I'm root on the database so rights shouldn't be a problem either.
You need to add a db.commit() to commit your changes before you db.close()!
I am using Ubuntu 9.04
I have installed the following package versions:
unixodbc and unixodbc-dev: 2.2.11-16build3
tdsodbc: 0.82-4
libsybdb5: 0.82-4
freetds-common and freetds-dev: 0.82-4
python2.6-dev
I have configured /etc/unixodbc.ini like this:
[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
Driver = /usr/lib/odbc/libtdsodbc.so
Setup = /usr/lib/odbc/libtdsS.so
CPTimeout =
CPReuse =
UsageCount = 2
I have configured /etc/freetds/freetds.conf like this:
[global]
tds version = 8.0
client charset = UTF-8
text size = 4294967295
I have grabbed pyodbc revision 31e2fae4adbf1b2af1726e5668a3414cf46b454f from http://github.com/mkleehammer/pyodbc and installed it using "python setup.py install"
I have a windows machine with Microsoft SQL Server 2000 installed on my local network, up and listening on the local ip address 10.32.42.69. I have an empty database created with name "Common". I have the user "sa" with password "secret" with full privileges.
I am using the following python code to setup the connection:
import pyodbc
odbcstring = "SERVER=10.32.42.69;UID=sa;PWD=secret;DATABASE=Common;DRIVER=FreeTDS"
con = pyodbc.connect(odbcstring)
cur = con.cursor()
cur.execute("""
IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'testing')
DROP TABLE testing
""")
cur.execute('''
CREATE TABLE testing (
id INTEGER NOT NULL IDENTITY(1,1),
myimage IMAGE NULL,
PRIMARY KEY (id)
)
''')
con.commit()
Everything WORKS up to this point. I have used SQLServer's Enterprise Manager on the server and the new table is there.
Now I want to insert some data on the table.
cur = con.cursor()
# using web data for exact reproduction of the error by all.
# I'm actually reading a local file in my real code.
url = 'http://www.forestwander.com/wp-content/original/2009_02/west-virginia-mountains.jpg'
data = urllib2.urlopen(url).read()
sql = "INSERT INTO testing (myimage) VALUES (?)"
Now here on my original question, I was having trouble using cur.execute(sql, (data,)) but now I've edited the question, because following Vinay Sajip's answer below (THANKS), I have changed it to:
cur.execute(sql, (pyodbc.Binary(data),))
con.commit()
And insertion is working perfectly. I can confirm the size of the inserted data using the following test code:
cur.execute('SELECT DATALENGTH(myimage) FROM testing WHERE id = 1')
data_inside = cur.fetchone()[0]
assert data_inside == len(data)
Which passes perfectly!!!
Now the problem is on retrieval of the data back.
I am trying the common approach:
cur.execute('SELECT myimage FROM testing WHERE id = 1')
result = cur.fetchone()
returned_data = str(result[0]) # transforming buffer object
print 'Original: %d; Returned: %d' % (len(data), len(returned_data))
assert data == returned_data
However that fails!!
Original: 4744611; Returned: 4096
Traceback (most recent call last):
File "/home/nosklo/devel/teste_mssql_pyodbc_unicode.py", line 53, in <module>
assert data == returned_data
AssertionError
I've put all the code above in a single file here, for easy testing of anyone that wants to help.
Now for the question:
I want python code to insert an image file into mssql. I want to query the image back and show it to the user.
I don't care about the column type in mssql. I am using the "IMAGE" column type on the example, but any binary/blob type would do, as long as I get the binary data for the file I inserted back unspoiled. Vinay Sajip said below that this is the preferred data type for this in SQL SERVER 2000.
The data is now being inserted without errors, however when I retrieve the data, only 4k are returned. (Data is truncated on 4096).
How can I make that work?
EDITS: Vinay Sajip's answer below gave me a hint to use pyodbc.Binary on the field. I have updated the question accordingly. Thanks Vinay Sajip!
Alex Martelli's comment gave me the idea of using the DATALENGTH MS SQL function to test if the data is fully loaded on the column. Thanks Alex Martelli !
Huh, just after offering the bounty, I've found out the solution.
You have to use SET TEXTSIZE 2147483647 on the query, in addition of text size configuration option in /etc/freetds/freetds.conf.
I have used
cur.execute('SET TEXTSIZE 2147483647 SELECT myimage FROM testing WHERE id = 1')
And everything worked fine.
Strange is what FreeTDS documentation says about the text size configuration option:
default value of TEXTSIZE, in bytes. For text and image datatypes, sets the maximum width of any returned column. Cf. set TEXTSIZE in the T-SQL documentation for your server.
The configuration also says that the maximum value (and the default) is 4,294,967,295. However when trying to use that value in the query I get an error, the max number I could use in the query is 2,147,483,647 (half).
From that explanation I thought that only setting this configuration option would be enough. It turns out that I was wrong, setting TEXTSIZE in the query fixed the issue.
Below is the complete working code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pyodbc
import urllib2
odbcstring = "SERVER=10.32.42.69;UID=sa;PWD=secret;DATABASE=Common;DRIVER=FreeTDS"
con = pyodbc.connect(odbcstring)
cur = con.cursor()
cur.execute("""
IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'testing')
DROP TABLE testing
""")
cur.execute('''
CREATE TABLE testing (
id INTEGER NOT NULL IDENTITY(1,1),
myimage IMAGE NULL,
PRIMARY KEY (id)
)
''')
con.commit()
cur = con.cursor()
url = 'http://www.forestwander.com/wp-content/original/2009_02/west-virginia-mountains.jpg'
data = urllib2.urlopen(url).read()
sql = "INSERT INTO testing (myimage) VALUES (?)"
cur.execute(sql, (pyodbc.Binary(data),))
con.commit()
cur.execute('SELECT DATALENGTH(myimage) FROM testing WHERE id = 1')
data_inside = cur.fetchone()[0]
assert data_inside == len(data)
cur.execute('SET TEXTSIZE 2147483647 SELECT myimage FROM testing WHERE id = 1')
result = cur.fetchone()
returned_data = str(result[0])
print 'Original: %d; Returned; %d' % (len(data), len(returned_data))
assert data == returned_data
I think you should be using a pyodbc.Binary instance to wrap the data:
cur.execute('INSERT INTO testing (myimage) VALUES (?)', (pyodbc.Binary(data),))
Retrieving should be
cur.execute('SELECT myimage FROM testing')
print "image bytes: %r" % str(cur.fetchall()[0][0])
UPDATE: The problem is in insertion. Change your insertion SQL to the following:
"""DECLARE #txtptr varbinary(16)
INSERT INTO testing (myimage) VALUES ('')
SELECT #txtptr = TEXTPTR(myimage) FROM testing
WRITETEXT testing.myimage #txtptr ?
"""
I've also updated the mistake I made in using the value attribute in the retrieval code.
With this change, I'm able to insert and retrieve a 320K JPEG image into the database (retrieved data is identical to inserted data).
N.B. The image data type is deprecated, and is replaced by varbinary(max) in later versions of SQL Server. The same logic for insertion/retrieval should apply, however, for the newer column type.
I had a similar 4096 truncation issue on TEXT fields, which SET TEXTSIZE 2147483647 fixed for me, but this also fixed it for me:
import os
os.environ['TDSVER'] = '8.0'