Okay here is my code. Hopefully you can help me. I am using the MySQL lib called MySQLdb.
def createNick(self, user, nick):
try: # TRY STATEMENT HERE SO THE NICK CAN BE RECREATED
db = m.connect("host", "user", "password", "database")
cur = db.cursor()
cur.execute("CREATE TABLE nick_%s(name TEXT NOT NULL)" % user.lower())
cur.execute('INSERT INTO nick_%s(name) VALUES("%s")' % (user.lower(), nick))
db.commit()
except:
db = m.connect("host", "user", "password", "database")
cur = db.cursor()
cur.execute("DROP TABLE nick_%s" % user.lower())
cur.execute("CREATE TABLE nick_%s(name TEXT NOT NULL)" % user.lower())
cur.execute('INSERT INTO nick_%s(name) VALUES("%s")' % (user.lower(), nick))
db.commit()
def getNick(user):
db = m.connect("host", "user", "password", "database")
cur = db.cursor()
cur.execute("SELECT * FROM nick_%s" % user.lower())
nick = [nick[0] for nick in cur.fetchall()]
try: # TRY STATEMENT HERE JUST INCASE USER DID NOT MAKE ONE
return nick
except:
return user
self.createNick("username","<font color='#FFFF'>nickname</font>")
print self.getNick("username")
output: <font color=#FFF>nickname</font>
My problem is, every time I call the function it won't phrase the HTML correctly. I tried everything, can you help?
I wouldn't do that, I would use a specific data type for XML so that I save HTML to a datatype of type XML. Or I would not save HTML and insert the markup with a controller, or make my own midddleware language since it is usually not adviseable to save HTML in a database table.
Related
I have an issue returning a string from my database query.
First step was to create a database:
def create_database():
# database setup
try:
con = sqlite3.connect('db/mydb.db')
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS user (id INTEGER NOT NULL PRIMARY KEY, balance REAL NOT NULL, text TEXT NOT NULL)')
con.commit()
con.close()
except Error as e:
print('Failed to setup database.\n' + e)
exit(1)
def get_connection():
try:
con = sqlite3.connect('db/mydb.db')
return con
except:
print('Unable to connect to database. Please try again later.\n')
exit(1)
My second step was creating a user and add him with INSERT to my database:
def create_user(user_id : int):
balance = 0.0; # base unit = USD
text = create_text()
# connect to database
con = get_connection()
cur = con.cursor()
cur.execute('INSERT INTO user (id, balance, text) VALUES (?, ?, ?)', (user_id, balance, text))
database = cur.execute('SELECT * FROM user').fetchone()
print(database)
con.commit()
con.close()
def create_text():
# do some stuff which creates my text
# the text is something like 'LNURL...'
return text
This is how the result of my database query looks like:
(393120847059091456, 0.0, 'LNURL1DP68GURN8GHJ7URP09JX7MTPDCHXGEF0D3H82UNVWQHKZURF9AMRZTMVDE6HYMP0XGMQA9V7RT')
If I try to query this database for my text it returns nothing/None. My print(text) just produces an empty new line.
def get_text(user_id : int):
# connect to database
con = get_connection()
cur = con.cursor()
cur.execute('SELECT text FROM user WHERE id=?', (user_id,))
text = cur.fetchone()
con.commit()
con.close()
print(text)
return text
I think my sqlite database used 32bit int values by default. So forcing it to use 64 bit when creating the table fixed my issue:
cur.execute('CREATE TABLE IF NOT EXISTS user (id INT8 PRIMARY KEY NOT NULL, balance REAL NOT NULL, text TEXT NOT NULL')
Than I can return my result of the query with this: return text[0]
I have an issue to run my SQL queries on a Postgres ElephantSql hosted:
This is my code to connect (except dynamo, user, password which are replaced by XXX
DATABASE_URL = 'postgres://YYYY:ZZZZ#drona.db.elephantsql.com:5432/YYYY'
# ---------------------------- CONNECT ELEPHANT DB
def ElephantConnect():
up.uses_netloc.append("postgres")
url = up.urlparse(DATABASE_URL)
conn = psycopg2.connect(dbname='YYYY',
user='YYYY',
password='ZZZZ',
host='drona.db.elephantsql.com',
port='5432'
)
cursor = conn.cursor()
# cursor.execute("CREATE TABLE notes(id integer primary key, body text, title text);")
#conn.commit()
# conn.close()
return conn
this code seems to connect well to db
My issue is when I want to delete a table:
def update(df, table_name, deleteYes= 'Yes'):
conn = ElephantConnect()
db = create_engine(DATABASE_URL)
cursor =conn.cursor()
if deleteYes == 'Yes': # delete
queryCount = "SELECT count(*) FROM {};".format(table_name)
queryDelete = "DELETE FROM {};".format(table_name)
count = db.execute(queryCount)
rows_before = count.fetchone()[0]
try:
db.execute(queryDelete)
logging.info('Deleted {} rows into table {}'.format(rows_before, table_name))
except:
logging.info('Deleted error into table {}'.format(table_name))
else:
pass
It seems when I run db.execute(queryDelete), it goes to the exception.
I have no message of error. But the query with count data is working...
thanks
I think that the reason for the error is because there are foreign keys against the table. In order to be sure, assign the exception into a variable and print it:
except Exception as ex:
print(ex)
By the way, if you want to quickly delete all of the rows from a table then
It will be much more efficient to truncate the table instead of deleting all the rows:
truncate table table_name
Delete is more useful when you want to delete rows under some conditions:
delete from table_name where ...
I have this code
import MySQLdb
db = MySQLdb.connect("localhost", "root", "password", "db_name")
cursor = db.cursor()
cursor.execute("INSERT INTO directedEdges (`originLbl`, `targetLbl`) VALUES
('user1#enron.com', 'user2#enron.com' )")
data = cursor.fetchone()
print data
but when I execute this script the output is None and and I can't insert the values in the db. Why ?
In a first moment I thought it was a problem whit db connection, but if I execute
import MySQLdb
db = MySQLdb.connect("localhost", "root", "password", "db_name")
cursor = db.cursor()
cursor.execute("SELECT * FROM directedEdges")
data = cursor.fetchone()
print data
I see the content of the table directedEdges.
Thanks
You issued the cursor.fetchone() command immediately after inserting into the database. You don't have any queried data like that. You need to have queried some data before using fetchone(). Try this:
import MySQLdb
db = MySQLdb.connect("localhost", "root", "password", "db_name")
cursor = db.cursor()
cursor.execute("INSERT INTO directedEdges (`originLbl`, `targetLbl`) VALUES
('user1#enron.com', 'user2#enron.com' )")
# Commit your insert
db.commit()
# Query for data
cursor.execute("SELECT * FROM directedEdges")
data = cursor.fetchone()
print data
When I create the DataBase CURRENT_users.db:
import sqlite3
conn = sqlite3.connect('CURRENT_users.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome TEXT NOT NULL,
email TEXT NOT NULL,
created_in DATE NOT NULL,
password TEXT NOT NULL
)
""")
print("Success! DATABASE created with success!")
conn.close()
import UserLoginUI_Part2_Tes
t1
And I insert the DATA:
import sqlite3
conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()
cursor.execute("""
INSERT INTO users (id, nome, email, created_in, password)
VALUES (001, "Renatinho", "renato.lenon#Outlook.com", 2005-4-21, "Plugxyvj9");
""")
conn.commit()
print("A new user has been incremented! Now,have fun!!!")
conn.close()
import UserInterface
In "UserInterface", I type "Renatinho" (that's my NOME data),it seems like that "IF" doesn't work!!
import sqlite3
conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()
user_INFO = cursor.execute(""" SELECT nome FROM users; """)
user_in_SCRIPT = str(input("Your credentials: USERNAME: \n>>>"))
logged_in = False;
if user_in_SCRIPT == user_INFO:
print("You are logged in! Enjoy your new account...")
logged_in = True;
else:
print("Error: Not a valid user or USERNAME!!")
conn.close()
And it ever shows me the ELSE "command block"..
Please,who can help me?
Thanks for everything...
PRINT OF THE ERROR:
You've called SQL SELECT but you need to fetch the data.
cursor.execute("SELECT nome FROM users")
user_INFO = cursor.fetchone()
This would return a tuple, so to get the string inside, take the zero index:
if user_in_SCRIPT == user_INFO[0]:
print("You are logged in! Enjoy your new account...")
logged_in = True
BTW, you're in Python, not JavaScript. You don't need to end statements with semicolons. :-)
I created a db table from terminal, and now i want to insert data to it using following code,sql_insert_reg statement which is used as sql insert command is same as that i use in terminal insert operations but using in python file does not insert data .I am learning use of mysql in flask,here's my code.This code does not give error but does nothing as i expect it to!
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'EmpData'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
class RegistrationForm(Form):
username = TextField('Username', [validators.Length(min=4, max=25)])
password = PasswordField('New Password', [
validators.Required(),
validators.EqualTo('confirm', message='Passwords must match')])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS', [validators.Required()])
#app.route('/register',methods=['GET','POST'])
def register():
form = RegistrationForm(request.form)
flash('login details')
session['tmp'] = 43
if request.method == 'POST' and form.validate():
username = form.username.data
password = form.password.data
sql_insert_reg = "INSERT INTO User(userName,password) VALUES(%s,%s)"
#flash(sql_insert_reg)
conn = mysql.connect()
cursor = mysql.get_db().cursor()
cursor.execute(sql_insert_reg,(username,password))
conn.commit()
return render_template('register.html',form=form)
this is the screenshot i uploaded below..please see the entries useId 2 then goes directly to 6 ..and i got to see this by altering the answer as suggested to me!!can anyone lookout the problem behind the scene!
Please help me!
This is what a typical INSERT statement looks like:
INSERT INTO table (column1,column2,column3) VALUES (value1,value2,value3);
Note that if your first column is auto-incremental (e.g. some sort of index), you can ommit that from the statement and just write it as follows:
INSERT INTO User (user_column, pass_column) VALUES ('foo', 'bar');
So... don't do this:
sql = "INSERT INTO Table VALUES(NULL,'%s','%s')"%(username,password)+";"
Do this instead:
sql = "INSERT INTO Table (col1, col2) VALUES (%s, %s)"
cursor.execute(sql, (value1, value2))
Why? Because that will sanitize your input and you don't end up registering Bobby Drop Table as a user.
If doing it that way doesn't do what you expect, please provide more detail on what is happening, what you're expecting and how you know that you don't have what you expect to see.
this could be your problem
ursor.execute(sql_insert_reg,(username,password))
looks like it should be
cursor.execute(sql_insert_reg,(username,password))
and if thats not it, i would just use sqlalchemy to generate the sql for you
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker,scoped_session
import sqlalchemy as sa
Model = declarative_base()
engine = sa.create_engine('mysql://DB_USERNAME:DB_PASSWORD#DB_HOST:DB_PORT/DB_NAME')
Session = scoped_session(sessionmaker(bind=engine))
db_session = Session()
class User(Model):
__tablename__ = 'users'
id = sq.Column(sq.Integer,primary_key=True)
username = sq.Column(sq.String(255),nullable=False,unique=True)
password = sq.Column(sq.Text,nullable=False)
then if you want to manipulate the data you can change this from above
username = form.username.data
password = form.password.data
sql_insert_reg = "INSERT INTO User(userName,password) VALUES(%s,%s)"
#flash(sql_insert_reg)
conn = mysql.connect()
cursor = mysql.get_db().cursor()
ursor.execute(sql_insert_reg,(username,password))
conn.commit()
to this
user = User(username=form.username.data,password=form.password.data)
db_session.add(user)
db_session.commit()
I changed some code and found that instead of using the above lines of code in mysql i got this magic!
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()