I have some code that links to Access and works fine with adodbapi, except for one niggling issue which I cant resolve. Basically I want to create a new table in Access with the Column Headings "Key" and "Value" but it doenst seem to work unless I include the commas which I dont want.
I get the following error:
adodbapi.adodbapi.DatabaseError: (-2147352567, 'Exception occurred.', (0, u'Microsoft JET Database Engine', u'Syntax error in field definition.', None, 5003292, -2147217900), None)
import adodbapi
# create the DSN execution string and point it to the desired Database
database = 'D:\Temp.mdb'
constr = 'Provider=Microsoft.Jet.OLEDB.4.0; Data Source=%s ' % database
conn = adodbapi.connect(constr)
# create a cursor
cur = conn.cursor()
# below doesnt work
cur.execute('CREATE TABLE OtherInfo(Key VARCHAR(100), Value VARCHAR(100))')
# but this does
cur.execute('CREATE TABLE OtherInfo(Key2 VARCHAR(100), Value2 VARCHAR(100))')
# so does this
cur.execute('CREATE TABLE OtherInfo('Key' VARCHAR(100), 'Value' VARCHAR(100))')
# this also fails unless similar to above
cur.execute("INSERT INTO OtherInfo(Key,Value) VALUES('AppName','XXX')")
# close the cursor and connection
conn.commit() # this saves all of the changes made above
cur.close()
conn.close()
How can I make it insert Column headings and Data as {Key, Value} without having to resort to 'Key' etc as the program which uses this table cannot reference other names?
Thanks for any help.
Figured it out, it needs a [wrapper] to work as below:
cur.execute('CREATE TABLE OtherInfo([Key] VARCHAR(100), [Value] VARCHAR(100))')
Thanks to anyone who took the trouble to view.
Related
I am running this script and want to create a table by passing values in psql query using variables. So, that I can create multiple table in one go. But this cur.execute("CREATE TABLE IF NOT EXISTS(%s, %s)",[table_name, comp_schema]) line is throwing error. How can I write this query to create a table with the given schema?
import psycopg2
conn = psycopg2.connect(database="review_check", user = "xxx", password = "xxx",)
cur = conn.cursor()
print ("Opened database successfully")
comp_schema = """
as_of_date DATE PRIMARY KEY NOT NULL,
verified_reviews INTEGER,
lsa_total_reviews INTEGER
"""
table_name = 'comp_first'
cur.execute("CREATE TABLE IF NOT EXISTS(%s, %s)",[table_name, comp_schema])
conn.commit()
conn.close()
Use the psycopg2.sql module to compose a query dynamically. see https://www.psycopg.org/docs/sql.html.
There's a couple of errors here, in both the SQL syntax and the Python:
cur.execute("CREATE TABLE IF NOT EXISTS(%s, %s)",[table_name, comp_schema])
should be
cur.execute("CREATE TABLE IF NOT EXISTS %s (%s)"%(table_name, comp_schema))
It might be easier during development to build the query in a separate variable first, then print it to see if it looks right:
test = "CREATE TABLE IF NOT EXISTS %s (%s)"%(table_name, comp_schema)
print(test)
>>CREATE TABLE IF NOT EXISTS comp_first (
as_of_date DATE PRIMARY KEY NOT NULL,
verified_reviews INTEGER,
lsa_total_reviews INTEGER
)
I would like to "Add primary or foreign key" to table made using to_sql of Python dataframe. Here is some of my Python code.
This causes "sqlite3.OperationalError: no such table: is_year_002620"
But I checked is_year_002620 table created.
I have no idea why this isn't working. How can I "add primary key" to table made by to_sql?
for i in range(startrow, endrow):
if df is not None:
table_name = 'is_year_' + code #code is variable of 6 digit number and its number is about 1,800
df.to_sql(table_name, conn, if_exists='append', index=False)
conn.cursor().execute("""ALTER TABLE" %s "ADD PRIMARY KEY (code)""" %(table_name))
I write a python code to create a table,but when I open DB browser for SQLite, it does not the table I have created, I am new to database, so can anyone tell me what is wrong with it ? Many thanks!
import sqlite3
conn = sqlite3.connect('test1.sqlite')
cur = conn.cursor()
cur.execute('''
DROP TABLE IF EXISTS Test''')
cur.execute('''
CREATE TABLE Test (azaz TEXT, count INTEGER)''')
cur.execute('''INSERT INTO Test (azaz, count)
VALUES ( 'aa', 1 )''' )
conn.commit()
conn.close()
image link:imgur.com/epfar.png
Your code is right and if you try:
import sqlite3
conn = sqlite3.connect('test1.sqlite')
row = conn.execute('SELECT * FROM Test').fetchone()
print("azaz=", row[0])
print("count=", row[1])
You will see this output:
('azaz=', u'aa')
('count=', 1)
So the table has been created and values has been inserted in the table.
I have just tested your code and it works flawlessly. I have used python-3.5 and DB Broswer for sqlite, tested on window 7 pro.
So I found this really useful piece of code earlier that created entry boxes and when they were created I could edit what was inside of them. The data that was loaded in was taken from an SQL table. Once I have made edits to the entry boxes, I want to submit the data to overwrite the data that had previously been in that sql record, as it it was being edited. The code I found was this:
for item in selectedetails:
entry = Entry(top2)
entry.insert(0, item)
entry.pack()
entries.append(entry)
I want it to be able to enter an sql code. I have tried this but it doesn't work. I think I am doing it wrong.
def submitedit():
for entry in entries:
print(entry.get())
db = sqlite3.connect('TestFile')
cursor = db.cursor()
cursor.execute('''UPDATE Table SET ID=?, Name=?, Desc=? WHERE ID=?''',
("?"," ?"," ?").format(entry.get()))
cursor.close()
db.commit()
db.close()
I have also tried this:
db = sqlite3.connect('TestFile')
cursor = db.cursor()
cursor.execute('''UPDATE Table SET ID=?, Name=?, Desc=? WHERE ID=?''',
(entry.get())
cursor.close()
db.commit()
db.close()
Thanks.
with sqlite3.connect('TestFile') as db:
cursor = db.cursor()
cursor.row_factory = sqlite3.Row
sql = "UPDATE Table Name=?, Desc=? WHERE ID=?"
cursor.execute(sql,(Name,Descr))
db.commit()
Note that the order that you put your values in cursor.execute line must match up to the order used in sql variable, otherwise the wrong values will be used at the wrong time. Also i have taken out set ID due to that being what you are searching off which im guessing is your primary key, in databases you should not edit the primary key. The primary key should be auto incremented as well.
I have just started using MySQLdb in python. I am able to create table but when I try to insert, no rows are inserted into the table and its shows that table is still empty.
import MySQLdb
db = MySQLdb.connect("localhost","root","shivam","test")
cursor = db.cursor()
s = "DROP TABLE IF EXISTS batting"
cursor.execute(s)
s = """create table batting (
name varchar(50) primary key,
matches integer(5),
innings integer(5),
runs integer(5),
highest integer(3),
strikerate integer(3),
hundreds integer(3),
fifties integer(3)
)"""
cursor.execute(s)
s = """insert into batting(name) values(
"shivam")"""
cursor.execute(s)
db.close()
Where I could be going wrong?
You forgot to commit your connection. Simply add:
cursor.execute(s)
db.commit()
Have a look at this. It explains why you need to commit