Hello everyone I have this sql file :
Student.sql
Select * from student where age > 18;
Delet student_ name , studen_id if age > 18 ;
Commit;
Using cx_oracle pip
Any help
Instead of executing a file, you could execute have the query defined in your code.
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('Host Name', 'Port Number', service_name='Service Name') #if needed, place an 'r' before any parameter in order to address any special character such as '\'.
conn = cx_Oracle.connect(user=r'User Name', password='Personal Password', dsn=dsn_tns) #if needed, place an 'r' before any parameter in order to address any special character such as '\'. For example, if your user name contains '\', you'll need to place 'r' before the user name: user=r'User Name'
query = """
Select * from student where age > 18;
DeletE student_ name , studen_id if age > 18
"""
c = conn.cursor()
c.execute(query) # use triple quotes if you want to spread your query across multiple lines
print('Result', c)
#conn.close()
As other replies noted you can only execute a statement at a time with cx_Oracle. However you can write a wrapper to read your SQL files and execute each statement. This is a lot easier if you restrict the SQL syntax (particularly regarding line terminators). For an example, see https://github.com/oracle/python-cx_Oracle/blob/master/samples/SampleEnv.py#L116
Related
fairly new to SQL in general. I'm currently trying to bolster my general understanding of how to pass commands via cursor.execute(). I'm currently trying to grab a column from a table and rename it to something different.
import mysql.connector
user = 'root'
pw = 'test!*'
host = 'localhost'
db = 'test1'
conn = mysql.connector.connect(user=user, password=pw, host=host, database=db)
cursor = conn.cursor(prepared=True)
new_name = 'Company Name'
query = f'SELECT company_name AS {new_name} from company_directory'
cursor.execute(query)
fetch = cursor.fetchall()
I've also tried it like this:
query = 'SELECT company_name AS %s from company_directory'
cursor.execute(query, ('Company Name'),)
fetch = cursor.fetchall()
but that returns the following error:
stmt = self._cmysql.stmt_prepare(statement)
_mysql_connector.MySQLInterfaceError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? from company_directory' at line 1
I'm using python and mySQL. I keep reading about database injection and not using string concatenation but every time I try to use %s I get an error similar to the one below where. I've tried switching to ? syntax but i get the same error.
If someone could ELI5 what the difference is and what exactly database injection is and if what I'm doing in the first attempt qualifies as string concatenation that I should be trying to avoid.
Thank you so much!
If a column name or alias contains spaces, you need to put it in backticks.
query = f'SELECT company_name AS `{new_name}` from company_directory'
You can't use a placeholder for identifiers like table and column names or aliases, only where expressions are allowed.
You can't make a query parameter in place of a column alias. The rules for column aliases are the same as column identifiers, and they must be fixed in the query before you pass the query string.
So you could do this:
query = f"SELECT company_name AS `{'Company Name'}` from company_directory'
cursor.execute(query)
My variable values are derived from the edited grid cell. The function works but the edited field name is named "Read". I fixed it by changing the column name, but I am curious why that is an error and if there are any other field name titles I should avoid.
Message=(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Read = 'ALL' where User_ID = 'j_adams58'' at line 1")
Table fields
| User_ID | Password | Read | Edit |
def onCellChanged(self,event):
#Establish connection
self.connect_mysql()
#Update database
key_id = str(self.GetCellValue(event.GetRow(),1))
target_col = str(self.GetColLabelValue(event.GetCol()))
key_col = str(self.GetColLabelValue(1))
nVal = self.GetCellValue(event.GetRow(),event.GetCol())
sql_update = f"""Update {tbl} set {target_col} = %s where {key_col} = %s"""
row_data = ''
self.cursor.execute(sql_update, (nVal, key_id,))
#Close connection
self.close_connection()
Read is a reserved keyword in MySQL, so you shouldn't use it as a column name, but if you really need to, you should be able to access it by putting single backticks around it, like `Read`, but again, it's really bad style and you shouldn't do it. You should also avoid using other keywords, but it's usually best to try the queries you'll run in SQL first so you can check if you can.
See: https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-R
I'm trying to write code where after giving name and email input in the command prompt it should update the data in the Postgres database. English is not my first language, but I'll try my best to describe my situation.
So basically when typing in the cmd:
python myProgram.py jacob8 jacob8#company.com
It should update the jacob8 in the username column and jacob8#company.com in the email column.
So my code is like this:
import sys
import psycopg2
conn = psycopg2.connect("user=nana password=nana dbname=nana host=localhost")
cur = conn.cursor()
userName = str(sys.argv[1])
eMail = str(sys.argv[2])
cur.execute('UPDATE "table" SET "user_name" = userName WHERE "address"=%s', (mac,))
cur.execute('UPDATE "table" SET "user_email" = eMail WHERE "address"=%s', (mac,))
conn.commit()
...but for some reason userName that Im using where I'm trying to SET, doesn't recognize the userName that I assigned as sys.argv[1] and the same goes about eMail. When I'm adding them inside single quotation marks, it's recognized, but it messes up (makes the rest of the line green) the rest of the line starting with WHERE.
I also tried to put sys.argv[1] and sys.argv[2] straight into SET line (like UPDATE "table" SET "user_name" = sys.argv[1] WHERE) but it gives me the same kind of problem - it wont recognize the import sys anymore.
What am I missing here? It's clearly something to do with how to add quotation marks but I can't find the correct way..
You need placeholders for all locations where you want to substitute parameterized data -- so not just mac, but also userName and eMail.
Personally, for readability's sake, I'd write this as just one query doing both updates, as follows:
query = '
UPDATE table
SET user_name = %(name)s, user_email = %(email)s
WHERE address = %(mac)s
'
cur.execute(query, {'name': userName, 'email': eMail, 'mac': mac})
That said, the shortest possible change is just:
cur.execute('UPDATE "table" SET "user_name" = %s WHERE "address"=%s', (userName, mac,))
cur.execute('UPDATE "table" SET "user_email" = %s WHERE "address"=%s', (eMail, mac,))
I want to use sqlite3 to deal with data in Ubuntu with python. But I always failed and get errors. Codes related to database are as follows:
sqlite = "%s.db" % name
#connnect to the database
conn = sqlite3.connect(sqlite)
print "Opened database successfully"
c = conn.cursor()
#set default separator to "\t" in database
c.execute(".separator "\t"")
print "Set separator of database successfully"
#create table data_node
c.execute('''create table data_node(Time int,Node Text,CurSize int,SizeVar int,VarRate real,Evil int);''')
print "Table data_node created successfully"
node_info = "%s%s.txt" % (name,'-PIT-node')
c.execute(".import %\"s\" data_node") % node_info
print "Import to data_node successfully"
#create table data_face
data_info = "%s%s.txt" % (name,'-PIT-face')
c.execute('''create table data_face(Time int,Node Text,TotalEntry real,FaceId int,FaceEntry real,Evil int);''')
c.execute(".import \"%s\" data_face") % face_info
#get the final table : PIT_node
c.execute('''create table node_temp as select FIRST.Time,FIRST.Node,ROUND(FIRST.PacketsRaw/SECOND.PacketsRaw,4) as SatisRatio from tracer_temp FIRST,tracer_temp SECOND WHERE FIRST.Time=SECOND.Time AND FIRST.Node=SECOND.Node AND FIRST.Type='InData' AND SECOND.Type='OutInterests';''')
c.execute('''create table PIT_node as select A.Time,A.Node,B.SatisRatio,A.CurSize,A.SizeVar,A.VarRate,A.Evil from data_node A,node_temp B WHERE A.Time=B.Time AND A.Node=B.Node;''')
#get the final table : PIT_face
c.execute('''create table face_temp as select FIRST.Time,FIRST.Node,FIRST.FaceId,ROUND(FIRST.PacketsRaw/SECOND.PacketsRaw,4) as SatisRatio,SECOND.Packets from data_tracer FIRST,data_tracer SECOND WHERE FIRST.Time=SECOND.Time AND FIRST.Node=SECOND.Node AND FIRST.FaceId=SECOND.FaceId AND FIRST.Type='OutData' AND SECOND.Type='InInterests';''')
c.execute('''create table PIT_face as select A.Time,A.Node,A.FaceId,B.SatisRatio,B.Packets,ROUND(A.FaceEntry/A.TotalEntry,4),A.Evil from data_face as A,face_temp as B WHERE A.Time=B.Time AND A.Node=B.Node AND A.FaceId = B.FaceId;''')
conn.commit()
conn.close()
These sql-commands are right. When I run the code, it always shows sqlite3.OperationalError: near ".": syntax error. So how to change my code and are there other errors in other commands such as create table?
You have many problems in your code as posted, but the one you're asking about is:
c.execute(".separator "\t"")
This isn't valid Python syntax. But, even if you fix that, it's not valid SQL.
The "dot-commands" are special commands to the sqlite3 command line shell. It intercepts them and uses them to configure itself. They mean nothing to the actual database, and cannot be used from Python.
And most of them don't make any sense outside that shell anyway. For example, you're trying to set the column separator here. But the database doesn't return strings, it returns row objects—similar to lists. There is nowhere for a separator to be used. If you want to print the rows out with tab separators, you have to do that in your own print statements.
So, the simple fix is to remove all of those dot-commands.
However, there is a problem—at least one of those dot-commands actually does something:
c.execute(".import %\"s\" data_node") % node_info
You will have to replace that will valid calls to the library that do the same thing as the .import dot-command. Read what it does, and it should be easy to understand. (You basically want to open the file, parse the columns for each row, and do an executemany on an INSERT with the rows.)
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am porting a tcl script to python, because I can't seem to get the tclSqlite thing going on my Nokia N810. The script prompts for inputs, passes them to a sqlite db with 3 tables: Notes, Tags, and a NotesXTags many-to-many tbl. There are triggers that keep me from storing any tags more than once. Being a noob/hobbyist I went line by line through the tcl script replacing each with a Python line. Not very Pythonic, but I'm a hobbyist with no intention of using the language after I get this one script to work on N810. I did look at every Q&A S.O. suggested and I've been working on this for hours. I've got at least 3 bugs-of-ignorance. A chunk of the script in a module called 'pythonmakenote.py':
the crunch-bang ... and some comments ....
import sys, tty
import sqlite3
def mn():
conn = sqlite3.connect('/home/j...notes.sqlite')
db = conn.cursor()
tagsofar =db.execute('select tag_text from tag')
print tagsofar
print "Enter note text, remember to let console wrap long lines"
notetxt = input("note: ")
print "Enter 1 or more tags separated by spaces"
taglist = input("tags: ")
taglist = taglist.split(" ")
db.execute('INSERT INTO note (note_txt) VALUES (?)', notetxt)
db.commit
fknote = db.execute('select last_insert_rowid()')
#records new tags since db trigger stops dups, updates many-many tbl
for tagtxt in taglist:
db.execute('INSERT INTO tag VALUES (?)',tagtxt)
db.commit
fktag = db.execute('select rowid from tag where tag_text = (?)',tagtxt)
db.execute('INSERT INTO fkeys VALUES (?,?)',fknote,fktag)
db.commit
So I do 'import pythonmakenote'. So far so good. I type 'mn' and get an error:
>>> mn
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'mn' is not defined
Then I try this:
>>> from pythonmakenote import mn
>>> mn
<function mn at 0xb76b2a74>
But 'mn' still doesn't work. So I remove the Def altogether and copy the file and name it 'mn.py' and it sort-of works...
>>> import mn
<sqlite3.Cursor object at 0xb75fb740>
Enter note text, remember to let console wrap long lines
note: 'this is a note'<--------------------------Quotes are a MUST (but not in tcl version)
Enter 1 or more tags separated by spaces
tags: 'dev'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mn.py", line 19, in <module>
db.execute('INSERT INTO note (note_txt) VALUES (?)', notetxt)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 14 supplied.<-----------------------------Huh?
Where in the world are the S.O. instructions on code block tags and other markdown?
Why can't I Def mn in a module and use it? Is Python: NameError: global name 'foobar' is not defined pertinent? (to my problem)
I've got several other Defs to do for getting notes by tag, getting the tag list, etc.. and I thought they could all go in one module.
I don't want to put quotes around my inputs (the notes or the space-delimited tag list). Is that doable? I have the import tty thing in there but I'm not using it (don't know how but I'm beginning to suspect I'll have to learn)
If I put 3 tags in when prompted, without quotes, I get the 'unexpected EOF' error. Why?
I see strings are immutable so maybe assigning the list/split to a var that was a string before could be a problem?
Where does sqlite get '14' bindings supplied? I'm splitting on the space char but it's being ignored (because I'm doing it wrong)?
Would it be easier to do my little project in Bash?
Thanks to anyone who takes the time to get this far. I have a bad habit of needing help in areas off-topic in S.U. and too noob-RTFM here. I struggled a little with the tcl version but it now works like a champ. I expected Python to be somewhat straightforward. Still think it might be.
edit: WOW. A bunch of newlines got stripped out. Sorry I have no idea how to fix. I'm off to see if "raw_input" works better.
You'll want raw_input instead of input in your script. input evaluates what you type, which is why you have to enter quotes.
You can markdown code using the {} buttons above the input window. That actual markdown for code is a preceding 4 spaces.
db.commit needs to be db.commit().
If you do this:
>>> import pythonmakenote
To run mn do this:
>>> pythonmakenote.mn()
You can also do:
>>> from pythonmakenote import mn
>>> mn()
For lines like:
db.execute('INSERT INTO note (note_txt) VALUES (?)', notetxt)
You need:
db.execute('INSERT INTO note (note_txt) VALUES (?)', (notetxt,))
execute expects a sequence, so if you pass a string, it acts as a sequence of single characters, hence your 14 bindings error (it was a string of 14 characters). (xxx,) is the syntax for a 1-element tuple. Making it a list [xxx] would work too.
Here's my best guess at something that works. I don't have your database:
import sys
import sqlite3
def mn():
conn = sqlite3.connect('data.db')
db = conn.cursor()
db.execute('select tag_text from tag')
tagssofar = db.fetchall()
print tagssofar
print "Enter note text, remember to let console wrap long lines"
notetxt = raw_input("note: ")
print "Enter 1 or more tags separated by spaces"
taglist = raw_input("tags: ")
taglist = taglist.split()
db.execute('INSERT INTO note (note_txt) VALUES (?)', [notetxt])
conn.commit()
db.execute('select last_insert_rowid()')
fknote = db.fetchone()[0]
print fknote
#records new tags since db trigger stops dups, updates many-many tbl
for tagtxt in taglist:
db.execute('INSERT INTO tag VALUES (?)',[tagtxt])
conn.commit()
db.execute('select rowid from tag where tag_text = (?)',[tagtxt])
fktag = db.fetchone()[0]
print fktag
db.execute('INSERT INTO fkeys VALUES (?,?)',[fknote,fktag])
conn.commit()
There are a couple of things going on here. First, mn does not return anything, you would want something like:
>>> def mn():
... conn = sqlite3.connect('tester.db')
... cur = conn.cursor()
... return cur
...
>>> c = mn()
This leaves an open connection, so when you are done with c you would call:
>>> c.connection.close()
Also, the executing on the cursor does not return anything, you need to call some fetch method, ie fetchone or fetchall. Putting a few of these things together I would start to modify as follows:
import sys, tty
import sqlite3
def mn():
conn = sqlite3.connect('/home/j...notes.sqlite')
cur = conn.cursor()
return cur
db = mn()
tags_so_far = db.execute('select tag_text from tag').fetchall()
print tags_so_far
print "Enter note text, remember to let console wrap long lines \n"
notetxt = raw_input("note: ")
print "Enter 1 or more tags separated by spaces \n"
taglist = raw_input("tags: ").split()
db.execute('INSERT INTO note (note_txt) VALUES (?)', notetxt)
db.commit()
fknote = db.execute('select last_insert_rowid()').fetchone()[0]
#records new tags since db trigger stops dups, updates many-many tbl
for tagtxt in taglist:
db.execute('INSERT INTO tag VALUES (?)', (tagtxt,))
db.commit()
fktag = db.execute('select rowid from tag where tag_text = (?)',tagtxt)
db.execute('INSERT INTO fkeys VALUES (?,?)',fknote,fktag)