I've tried making an update to my sqlite3 table but it doesn't seem to work.
marks = "My long name here"
conn = sqlite3.connect('mydb.db')
cur=conn.cursor()
cur.execute("UPDATE '" + str(marks) +"' SET (ENG,KIS,MAT,BIO) = (-1,-1,-1,-1) WHERE (ENG,KIS,MAT,BIO) =('nan','nan','nan','nan')")
conn.commit()
conn.close()
I can't see nay error in my code.
You don't need 4 separate statements.
You can do it in 1 statement with CASE expressions:
UPDATE tablename
SET ENG = CASE WHEN ENG = 'nan' THEN -1 ELSE ENG END,
KIS = CASE WHEN KIS = 'nan' THEN -1 ELSE KIS END,
MAT = CASE WHEN MAT = 'nan' THEN -1 ELSE MAT END,
BIO = CASE WHEN BIO = 'nan' THEN -1 ELSE BIO END
WHERE 'nan' IN (ENG,KIS,MAT,BIO)
This worked, separating them.
marks = "My long name here"
conn = sqlite3.connect('mydb.db')
cur=conn.cursor()
cur.execute("UPDATE '" + str(marks) + "' SET ENG=-1 WHERE ENG='nan'")
cur.execute("UPDATE '" + str(marks) + "' SET KIS=-1 WHERE KIS='nan'")
cur.execute("UPDATE '" + str(marks) + "' SET MAT=-1 WHERE MAT='nan'")
cur.execute("UPDATE '" + str(marks) + "' SET BIO=-1 WHERE BIO='nan'")
conn.commit()
conn.close()
Rather than this.
marks = "My long name here"
conn = sqlite3.connect('mydb.db')
cur=conn.cursor()
cur.execute("UPDATE '" + str(marks) +"' SET (ENG,KIS,MAT,BIO) = (-1,-1,-1,-1) WHERE (ENG,KIS,MAT,BIO) =('nan','nan','nan','nan')")
conn.commit()
conn.close()
Related
Hello I cant figure out the solution for that problem. I searched on google but got no answer.
I'm new to db. so maybe its a dumb question :).
class Users:
def __init__(self, tablename="users", userId="userId", password="password", username="username"):
self.__tablename = tablename
self.__userId = userId
self.__password = password
self.__username = username
conn = sqlite3.connect('test.db')
print("open database successfully")
str = "CREATE TABLE IF NOT EXISTS " + tablename + "(" + self.__userId + " " + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
str += " " + self.__password + "TEXT NOT NULL ,"
str += " " + self.__username + "TEXT NOT NULL )"
conn.execute(str)
print("Table created successfully")
conn.commit()
conn.close()
def insert_user(self, username, password):
conn = sqlite3.connect('test.db')
str_insert = "INSERT INTO " + self.__tablename + " (" + self.__username +"," + self.__password + ") VALUES (" + "'" +username + "'" + "," + "'" +password +"'" +");"
print(str_insert)
conn.execute(str_insert)
conn.commit()
conn.close()
print("Record created successfully")
u = Users()
u.insert_user("yonatan#gmail.com", "123456")
Problem is here :
str = "CREATE TABLE IF NOT EXISTS " + tablename + "(" + self.__userId + " " + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
str += " " + self.__password + "TEXT NOT NULL ,"
str += " " + self.__username + "TEXT NOT NULL )"
Indeed, concatenate "username" and "TEXT NOT NULL" will give "usernameTEXT NOT NULL", without space between "username" and "TEXT"
You can see this if you execute the following query :
conn.execute("SELECT * from sqlite_master").fetchall()
This gives you :
[
('table', 'users', 'users', 2, 'CREATE TABLE users(userId INTEGER PRIMARY KEY AUTOINCREMENT , passwordTEXT NOT NULL , usernameTEXT NOT NULL )'),
('table', 'sqlite_sequence', 'sqlite_sequence', 3, 'CREATE TABLE sqlite_sequence(name,seq)')
]
Which is clearly a mess.
When you work with sqlite3, a good practice is to use the following syntax, which will avoid you a lot of space mistakes :
conn.execute(
f"CREATE TABLE IF NOT EXISTS {tablename}"
f"({self.__userId} INTEGER PRIMARY KEY AUTOINCREMENT,"
f"{self.__password} TEXT NOT NULL, {self.__username} TEXT NOT NULL)"
)
I've been trying to make my code works but can't find why won't it does what it does.
I'm trying to put data in my database, by it only seem to exec one ....
The code is :
def setCubesValues(value):
mysql.connection.autocommit(on=True)
tabVal = value.split(';;')
del tabVal[0]
for i in range(0, len(tabVal)):
tabi = tabVal[i]
cur = mysql.connection.cursor()
responseCur = cur.execute('SELECT * FROM idcudetoaction where id_cube = "' + tabi +'"')
if responseCur == 1:
curResultInsert = cur.execute('update idcudetoaction set action = "' + tabi +'" where id_cube = ' + str(i))
else:
curResultInsert = cur.execute('insert into idcudetoaction (id_cube, action) values (' + str(i)+', "' + tabi +'")')
return jsonify(curResultInsert);
Thing is I have 7 values, but only on that get put in the database ...
Any help ? :)
thx !
I have a python function that gets me version info like this:
def get_version_info(build_id, table_name='build_info'):
query = "SELECT `build_commit` FROM `" + table_name + "` WHERE `build_id` = %s "
args = (build_id)
#query = "SELECT `build_commit` FROM `" + table_name + "` WHERE `build_id` = " + build_id
build_commit = None
try:
dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
cursor.execute(query, args)
#cursor.execute(query)
row = cursor.fetchone()
if row is not None:
build_commit = row[0]
This functions always returns None no matter what.
And when I change this to use non-parameterized query like below. It always returns correct build_commit.
def get_version_info(build_id, table_name='build_info'):
query = "SELECT `build_commit` FROM `" + table_name + "` WHERE `build_id` = " + build_id
...
cursor.execute(query)
Is there something, I am missing out in the parameterized query for cursor.execute which is why it is failing.
I am moving data from MySQL to MSSQL - however I have a problem with insert into statement when I have ' in value.
for export i have used code below:
import pymssql
import mysql.connector
conn = pymssql.connect(host='XXX', user='XXX',
password='XXX', database='XXX')
sqlcursor = conn.cursor()
cnx = mysql.connector.connect(user='root',password='XXX',
database='XXX')
cursor = cnx.cursor()
sql= "SELECT Max(ID) FROM XXX;"
cursor.execute(sql)
row=cursor.fetchall()
maxID = str(row)
maxID = maxID.replace("[(", "")
maxID = maxID.replace(",)]", "")
AMAX = int(maxID)
LC = 1
while LC <= AMAX:
LCC = str(LC)
sql= "SELECT * FROM XX where ID ='"+ LCC +"'"
cursor.execute(sql)
result = cursor.fetchall()
data = str(result)
data = data.replace("[(","")
data = data.replace(")]","")
data = data.replace("None","NULL")
#print(row)
si = "insert into [XXX].[dbo].[XXX] select " + data
#print(si)
#sys.exit("stop")
try:
sqlcursor.execute(si)
conn.commit()
except Exception:
print("-----------------------")
print(si)
LC = LC + 1
print('Import done | total count:', LC)
It is working fine until I have ' in one of my values:
'N', '0000000000', **"test string'S nice company"**
I would like to avoid spiting the data into columns and then checking if there is ' in the data - as my table has about 500 fields.
Is there a smart way of replacing ' with ''?
Answer:
Added SET QUOTED_IDENTIFIER OFF to insert statement:
si = "SET QUOTED_IDENTIFIER OFF insert into [TechAdv].[dbo].[aem_data_copy]
select " + data
In MSSQL, you can SET QUOTED_IDENTIFIER OFF, then you can use double quotes to escape a singe quote, or use two single quotes to escape one quote.
I need to write a program which can,firstly, for ip adresses of people who saw my campaign on google, and then give me detailed information about each of these persons.
I have all information in postgres database and use python 3.5
Here is my code:
def get_connection(cursor_factory=None):
conn_string_pg = "host= '" + host + "' dbname = '" + dbname + "' user = '" + user + \
"' password = '" + password + "'"
if cursor_factory is None:
conn_pg = psycopg2.connect(conn_string_pg)
else:
conn_pg = psycopg2.connect(conn_string_pg,
cursor_factory=cursor_factory)
return conn_pg
def find_logs():
select = """ select ip_address from log_files o where o.url like
'%my_campaign'
"""
conn = get_connection(cursor_factory = RealDictCursor)
cur = conn.cursor()
cur.execute(select)
records = cur.fetchone()
for item in records:
select_2 = "select * from log_files where ip_address = %(item)s "
cur.execute(select_2)
logs = cur.fetchone()
return logs
print(find_logs())
cur.close()
Unfortunately I get this error:
psycopg2.ProgrammingError: syntax error at or near "%" LINE 1:
...elect * from web_logs.log_data where ip_address = %(item)s o...
Your string interpolation is incorrect. You're trying to insert the value of item into your select_2 statement, but you don't actually do the string interpolation, so you pass psycopg2 an invalid SQL statement. You want to do something like
select_2 = "select * from log_files where ip_address = {}".format(item)
It's because ip_address = %(item)s it's not a valid sql syntax. You should make string formatting before:
select_2 = "select * from log_files where ip_address = %(item)s " % {'item': item}
And the better way to do it is to give all the transformation to the postgres driver
select_2 = "select * from log_files where ip_address = %s "
cur.execute(select_2, (item, ))