I'm trying to insert data into sql table like this
conn = sqlite3.connect('Tags.db')
cur = conn.cursor()
input = open('word_freq_list.txt', 'r', encoding = 'UTF-8')
for word in input.read().split():
p = morph.parse(word)[0]
pos = p.tag.POS
case = p.tag.case
num = p.tag.number
gender = p.tag.gender
cur.execute(''' INSERT INTO Words_with_tags (POS, CASE, NUM, GENDER)
VALUES (?, ?, ?, ?)''', (pos, case, num, gender))
conn.commit()
But every I'm getting an error message:
sqlite3.OperationalError: near "CASE": syntax error
I can't understand why: column names are placed in the right order, the names are right too.
CASE is a Reserved Word, you can't use it as a column or variable name in your SQL query. Try using another column name instead of CASE.
Related
The main problem I am having is inserting the correct word id from one table to another based on the word the user had to guess.
cursor.execute (f"SELECT word_ID FROM WORDS WHERE word = puzzle_to_solve (SELECT puzzle_to_solve FROM WORDS WHERE word = puzzle_to_solve)")
conn.commit()
player_ID = cursor.lastrowid
statistics = (player_ID, word_ID, score)
cursor.execute (f"INSERT INTO STATISTICS ('{player_ID}', '{word_ID}', {score}) VALUES (?, ?, ?)", statistics)
conn.commit()
I expect the output to insert the correct player id, word id and score into the table in my database. The player id and score part of the query does work.
The error I am receiving is mentioned below:
sqlite3.OperationalError: near "SELECT": syntax error
This error is appearing in the select statement line of code.
update your query to this:
cursor.execute (f"SELECT word_ID, player_ID FROM WORDS WHERE word = puzzle_to_solve")
conn.commit()
import sqlite3 as db
def criar_grupos():
global cursor3,nome_grupo
nome_grupo = raw_input('name of group')
nome_criador = raw_input('new user')
conn3 = db.connect("tabela_grupos.db")
cursor3 = conn3.cursor()
cursor3.execute('CREATE TABLE IF NOT EXISTS groups (name string NOT NULL
UNIQUE)')
conn3.commit()
cursor3.execute("alter table grupos add column '%s' 'string'" %
nome_grupo)
cursor3.execute('UPDATE grupos SET ("nome"=?) WHERE name=?',
(nome_grupo, nome_criador))
criar_grupos()
I'm having a bad time trying to execute this function.
I keep getting the error message:
sqlite3.OperationalError: near "(": syntax error
What could I be doing wrong.?
INSERT INTO <table> (col1, col2, col5) VALUES ('val1','val2','val5');
Change this:
cursor3.execute('UPDATE grupos SET ("nome"=?) WHERE name=?', (nome_grupo, nome_criador))
To this:
cursor3.execute('INSERT INTO grupos (?) VALUES (?);', (nome_grupo, nome_criador))
my python program isn't working properly and it's something with the submit button and it gives me an error saying:
TypeError: 'str' object is not callable
help please. Here is the part of the code that doesn't work:
def submit():
g_name = ent0.get()
g_surname = ent1.get()
g_dob = ent2.get()
g_tutorg = ent3.get() #Gets all the entry boxes
g_email = ent4.get()
cursor = db.cursor()
sql = '''INSERT into Students, (g_name, g_surname, g_dob, g_tutorg, g_email) VALUES (?,?,?,?,?)'''
cursor.execute(sql (g_name, g_surname, g_dob, g_tutorg, g_email))
#Puts it all on to SQL
db.commit()
mlabe2=Label(mGui,text="Form submitted, press exit to exit").place(x=90,y=0)
I'm not sure what else you need so here's the rest of the SQL part that creates the table
cursor = db.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS Students(
StudentID integer,
Name text,
Surname text,
DOB blob,
Tutor_Grop blob,
Email blob,
Primary Key(StudentID));
""") #Will create if it doesn't exist
db.commit()
I've been trying so long and couldn't find a solution to this problem so if you can help that would be great thanks
problem maybe in your line:
cursor.execute(sql (g_name, g_surname, g_dob, g_tutorg, g_email))
try change it like this:
cursor.execute(sql, (g_name, g_surname, g_dob, g_tutorg, g_email))
Edit:
I call SQLite inserts in my simple app with this code:
data = (None, spath, sfile, sfilename, sha256hash, )
cur.execute("INSERT INTO filesoid VALUES (?, ?, ?, ?, ?)", data)
and it works ok.
You're not passing the values for your variables correctly. The way you've called cursor.execute(sql()) makes the interpreter think it's a function.
You need to format the sql string correctly:
sql = '''INSERT into Students, ({}, {}, {}, {}, {}) VALUES (?,?,?,?,?)'''.format(g_name, g_surname, g_dob, g_tutorg, g_email)
then use:
cursor.execute(sql)
EDIT:
or you may need to pass a tuple with data:
sql = '''INSERT into Students VALUES (?,?,?,?,?)'''
'data = (g_name, g_surname, g_dob, g_tutorg, g_email)
and then use
cursor.execute(sql, data)'
It depends on what those values actually are, and without seeing the database, I can't tell.
The problem is that I can't get the data from the text file to write to the database.
The text file is organized line by line ex:
John Doe 012-345-6789
As you can see, I've split the text and have all the categories straightened out.
But keep getting errors like InterfaceError: Error binding parameter 0 - probably un supported type or something about writing 47 entries to one field.
Thank you very much in advance.
import sqlite3
conn = sqlite3.connect('phoneNumbers.db')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS People ')
cur.execute('CREATE TABLE People (firstname TEXT, lastname TEXT, phonenumber TEXT)')
########
file = open('phoneNumbers.txt', 'r')
try:
file = open('phoneNumbers.txt', 'r')
except:
print "File not found"
data = file.read()
data = data.split()
for line in data:
first = data[0::3]
last = data [1::3]
num = data [2::3]
cur.execute('INSERT INTO People (firstname, lastname, phonenumber) VALUES (?, ?, ?)', (first, last, num))
conn.commit()
cur.execute('SELECT firstname, lastname, phonenumber FROM People')
for row in cur:
print row
conn.close()
There are a few problems with your code:
you are using the name file for your file, this is a built in name and you should rename it
you are opening the file twice, once before the try once in the try
Your actual problem:
first, last and num are lists and execute cannot use lists as parameters.
There is an executeManybut I do not like it in this case.
EDIT
Even slicker is reading line by line and using the with command.
with open('phoneNumbers.txt', 'r') as f:
for line in f:
data = line.split()
cur.execute('INSERT INTO People (firstname, lastname, phonenumber) VALUES (?, ?, ?)', (data[0], data[1], data[2]))
if 'str' in line:
break
Original
I would use a for with an index and then execute the INSERT in the loop like that.
try:
numbersFile = open('phoneNumbers.txt', 'r')
except:
print "File not found"
data = numbersFile.read()
data = data.split()
for i in range(0, len(data), 3):
first = data[i]
last = data[i+1]
num = data[i+2]
cur.execute('INSERT INTO People (firstname, lastname, phonenumber) VALUES (?, ?, ?)', (first, last, num))
conn.commit()
I'm have a stored procedure, code:
DECLARE #RC int
DECLARE #id varchar(13)
DECLARE #pw varchar(13)
DECLARE #depart varchar(32)
DECLARE #class varchar(12)
DECLARE #name varchar(12)
DECLARE #birthday varchar(10)
DECLARE #grade int
DECLARE #subgrade int
SELECT #id = 'test'
SELECT #pw = '12345'
SELECT #depart = 'none'
SELECT #class = 'GM'
SELECT #name = 'name'
SELECT #birthday = 'None'
SELECT #grade = 3
SELECT #subgrade = 2
EXEC #RC = [my_database].[dbo].[my_table] #id, #pw, #depart, #class, #name, #birthday, #grade, #subgrade
DECLARE #PrnLine nvarchar(4000)
PRINT 'Stored Procedure: my_database.dbo.my_table'
SELECT #PrnLine = ' Return Code = ' + CONVERT(nvarchar, #RC)
How i can make a raw sql query to create account using this procedure?
I'm using flask and pyodbc.
From the pyodbc documentation
To call a stored procedure right now, pass the call to the execute method using either a format your database recognizes or using the ODBC call escape format. (The ODBC driver will then reformat the call for you to match the given database.)
For SQL Server you would use something like this:
# SQL Server format
cursor.execute("exec sp_dosomething(123, 'abc')")
# ODBC format
cursor.execute("{call sp_dosomething(123, 'abc')}")
So to call your procedure
id_ = 'test'
pw = '12345'
depart = 'none'
class_ = 'GM'
name = 'name'
birthday = 'None'
grade = 3
subgrade = 2
sql = 'exec [my_database].[dbo].[my_table](?, ?, ?, ?, ?, ?, ?, ?)'
values = (id_, pw, depart, class_, name, birthday, grade, subgrade)
cursor.execute(sql, (values))
The accepted answer does not address the issue of capturing the return value from the stored procedure, which can be done like this:
id_ = 'test'
pw = '12345'
depart = 'none'
class_ = 'GM'
name = 'name'
birthday = 'None'
grade = 3
subgrade = 2
sql = """\
SET NOCOUNT ON;
DECLARE #RC int;
EXEC #RC = [my_database].[dbo].[my_sp] ?, ?, ?, ?, ?, ?, ?, ?;
SELECT #RC AS rc;
"""
values = (id_, pw, depart, class_, name, birthday, grade, subgrade)
cursor.execute(sql, values)
rc = cursor.fetchval() # pyodbc convenience method similar to cursor.fetchone()[0]
Don't forget SET NOCOUNT ON in your stored procedure.
Another flavour of Gord's answer is using OUTPUT and named parameters (to be defined within the Stored procedure) for clarity.
id_ = 'test'
pw = '12345'
depart = 'none'
class_ = 'GM'
name = 'name'
birthday = 'None'
grade = 3
subgrade = 2
sql = """\
DECLARE #RC int;
EXEC [my_database].[dbo].[my_sp] #RC OUTPUT, #id_=?, #pw=?, #depart=?, #class_=?, #name=?, #birthday=?, #grade=?, #subgrade=?;
SELECT #RC AS rc;
"""
values = (id_, pw, depart, class_, name, birthday, grade, subgrade)
cursor.execute(sql, values)
rc = cursor.fetchval()
With a cursor initialized by your connection, the sp can be called directly as follow
sql = " exec your_SP #codemp = ?, #fecha = ? "
prm = (dict['param1'], dict['param2'])
cursor.execute(qry, params)
After searching everywhere for this solution, i couldnt find a simplified version. All results seem to overcomplicate this that should be so easy to do. Heres my solution.
import pyodbc
import pandas as pd
import datetime as d
conn = pyodbc.connect('Driver=;'
'Server=;'
'Database=;'
'UID=;'
'PWD=;')
# define parameters to be passed in and out
quarter_date = d.date(year=2020, month=10, day=1)
SQL = r'exec TERRITORIES_SP #quarterStart = ' + "'" + str(quarter_date) + "'"
print(SQL)
try:
cursor = conn.cursor()
cursor.execute(SQL)
cursor.close()
conn.commit()
finally:
conn.close()
For MSSQL the correct format is this:
SQL = 'exec sp_UpdateUserGoogleAuthenticated ''?'', ''?'''
Try running the Stored Procedure in MSSQL in the SQL Query window and it will fail every time with () surrounding the ? marks. If you escape the single quotes it will allow for variables with spaces in them.