Actually I'm working on a Python and SQLite based url Shortener that will allow people to shorten their urls. But I'm in a trouble, so thats why I'm here hehe! So, my code is not inserting a thing into the database!
This is the connection and insertion code:
connection = sqlite3.connect(DBSource)
cursor = connection.cursor()
query = "INSERT INTO URLStorage VALUES('{0}','{1}','{2}')".format(urlFinal, urlprocessar, datetime.datetime.now())
#return(query)
cursor.execute(query)
If you want to take a look at the full source code to see if I mess something else, this is the link for it: https://github.com/vmesel/WP-A.CO
you want either a commit or close after you execute the query:
connection.commit()
or
connection.close()
Related
Now, I have a study about python sqlite3 database. I think it is very simple problem but not allow next step. Could help me?
There is print OK on vscode terminal, but not revised to DB file. I'm searching several times but I can not fix it.
If I execute the code, it not sorting on DB files.
import sqlite3
conn = sqlite3.connect('sqliteDB1.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM member")
temp123 = cursor. fetchall()
print(temp123)
cursor.execute("SELECT * FROM member ORDER BY -code")
temp321 = cursor.fetchall()
conn.commit
print(temp321)
conn.close()
A select statement just returns data from a database, it will not modify it. Moreover, tables in SQL databases are inherently unordered sets. They have no intrinsic value, and you should never rely on the order of the rows that happens to be returned unless you explicitly sort it with an order by clause.
I had no problem with SELECTing data in python from postgres database using cursor/execute. Just changed the sql to INSERT a row but nothing is inserted to DB. Can anyone let me know what should be modified? A little confused because everything is the same except for the sql statement.
<!-- language: python -->
#app.route("/addcontact")
def addcontact():
# this connection/cursor setting showed no problem so far
conn = pg.connect(conn_str)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
sql = f"INSERT INTO jna (sid, phone, email) VALUES ('123','123','123')"
cur.execute(sql)
return redirect("/contacts")
first look at your table setup and make sure your variables are named right in the right order, format and all that, if your not logging into the specific database on the sql server it won't know where the table is, you might need to send something like 'USE databasename' before you do your insert statement so your computer is in the right place in the server.
I might not be up to date with the language but is that 'f' supposed to be right before the quotes? if thats in ur code that'd probably throw an error unless it has a use im not aware of or its not relevant to the problem.
You have to commit your transaction by adding the line below after execute(sql)
conn.commit()
Ref: Using INSERT with a PostgreSQL Database using Python
I am trying to write a simple Python script that gets data from an API, stores it in a MySQL database, and performs some calculations on that data. I try fetch all data from a table where I just inserted some, but that query keeps returning None.
Part that doesn't work:
import MySQLdb
db = MySQLdb.connect("localhost", "stijn", "password", "GW2")
curs = db.cursor()
curs.execute("select gw2_id, naam from PrijzenMats")
for record in curs.fetchall():
curs2 = db.cursor()
curs2.execute("insert into MaterialPrijzenLogs(mat,prijs,tijd) values(%s, %s, %s)", (record[1], prijs, tijd))
db.commit()
curs2.execute("select prijs from MaterialPrijzenLogs")
top10 = len(curs2.fetchall())/10
print(str(len(curs2.fetchall())))
That last print keeps giving 0, even when I populate the table before running the script.
Full code
I solved the problem. Apparently when you call fetchall() it doesn't just get the data from the cursor like a normal getter in Java would do, but it also deletes the data from the cursor. In my code I called fetchall() first to initialize a variable, and after that I tried to print the length of curs2.fetchall(), which had become 0 at that point. This can be easily solved by adding something like myList = curs2.fetchall() directly after curs2.execute("select prijs from MaterialPrijzenLogs") and using the myList variable in the rest of the code instead of curs2.fetchall(). I did not include the declaration of that top10 variable in the code example in my original question because I thought it had nothing to do with the problem. I edited the question so future readers can easily understand the problem.
I'm using MysqlDB. Does it provide a way to execute multiple SELECT queries like mysqli_multi_query does? If not, is there a python library that would allow that?
There is executemany, but that's not what I'm looking for. I'm working with Sphinx and trying to get its batch queries to work.
I spent some time to dig in the source code of MySQLdb and the answer is YES you can do multiple queries with it:
import MySQLdb
db = MySQLdb.connect(user="username", db="dbname")
cursor = db.cursor()
batch_queries = '''
SELECT * FROM posts WHERE id=1;
SELECT * FROM posts WHERE id=2;
'''
cursor.execute(batch_queries)
print cursor.fetchone()
while cursor.nextset(): # iterate to next result set if there is any
print cursor.fetchone()
cursor.close()
Tested successfully in my localhost. Hope it helps.
I have a several postgres and mysql cursor objects exposed to me, created in some universe. How to find the database name (and other info about that db) from these cursor objects?
cursor.__dict__ gives nothing useful.
If you also have the connection (call it conn):
conn.info.dbname
I don't know about postgres but using MySQLdb you could always use the following:
cursor.execute("select database()")
db_name = cursor.fetchone()[0]
Maybe there's a cleaner way to do this...
Edit:
for other info it depends on what exactly you're looking for but for example to fetch table names
cursor.execute("show tables")
for r in cursor.fetchall():
print r[0]
There are many other functions available... Is there anything specific you're looking for?
for postgresql:-
cursor.execute("select current_database()")
db_name = cursor.fetchone()[0]