Fetch rows from Mysql and display it in html using Django - mysql

I am fairly new to Django. I want to know how to fetch rows from mysql and get it in views.py and send it to html where it will be displayed.
My views.py:
def fetchDate1(request):
query = request.session.get('query')
date1 = request.session.get('date1');
db = pymysql.connect(host="localhost", # your host
user="root", # username
passwd="=", # password
db="Golden") # name of the database
# Create a Cursor object to execute queries.
cur = db.cursor()
# Select data from table using SQL query.
stmt = "SELECT * FROM golden_response WHERE query LIKE '%s' AND DATE(updated_at) = '%s' " % (
query.replace("'", r"\'"), date1)
cur.execute(stmt)
if cur.rowcount is None:
return None
else:
rows = cur.fetchall()
row_headers = [x[0] for x in cur.description] # this will extract row headers
json_data = []
for result in rows:
json_data.append(dict(zip(row_headers, result)))
return json.dumps(json_data)
I don't know where I am going wrong. Have also saved required configuration in settings.py.
However when i try to run my program :
ProgrammingError: (1146, "Table 'Golden.django_session' doesn't exist")
Please help!!

I dare to hypothesize that you have not made the first migrations.
python manage.py makemigrations
python manage.py migrate
Moreover, you should check the database connection parameters in settings.py like this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db_name',
'USER': 'db_user',
'PASSWORD': 'db_user_password',
'HOST': 'db_server',
'PORT': '3306',
}
}

Related

Comparing user input to usernames in database

I am having an issue with comparing user input to a database of already used usernames. The database is working exactly how it is supposed to, but what seems like a simple task it proving to be more difficult than I thought. I figure I am missing something really simple! I get no error codes from the code but it does not print "username is taken" when the username is in fact in the database.
Thus far I have tried a for loop to compare the user's input to the database, I have tried making a list of the usernames in the database and iterating through the list to compare the user input:
### check to see if the user is already in the database
import mysql.connector
# Database entry
mydb = mysql.connector.connect(
host='Localhost',
port='3306',
user='root',
passwd='passwd',#changed for help
database='pylogin'
)
searchdb = 'SELECT username FROM userpass'
mycursor = mydb.cursor()
mycursor.execute(searchdb)
username = mycursor.fetchall()
print(username)
user = input('username')
for i in username:
if user == username:
print('username is taken')
else:
print("did not work")
Output that does not work:
[('Nate',), ('test',), ('test1',), ('test2',), ('n',), ('test4',)] username: n
('Nate',)
('test',)
('test1',)
('test2',)
('n',)
('test4',)
I expect the above code to iterate through each database entry and compare it to the user's input to verify that the username is not already taken. It should print "username is taken" instead it prints "did not work".
Welcome to Stack Overflow Nate!
You can use:
mycursor.execute("SELECT * FROM userpass WHERE username = ?", [(user)])
results = cursor.fetchall()
To create a variable called 'results' that stores all (*) of the column values for the record in the userpass database table where the username of the record is equal to the value of the user variable.
You can then use an if statement:
if results:
That is run if the results variable has a value (if there is a record with a username that is equal to the value of the user variable in the table) AKA if the username is taken.
This if statement can then, when run print 'username is taken'
The full code:
import mysql.connector
# Database entry
mydb = mysql.connector.connect(
host='Localhost',
port='3306',
user='root',
passwd='passwd',#changed for help
database='pylogin'
)
user = input('username')
mycursor.execute("SELECT * FROM userpass WHERE username = ?", [(user)])
results = cursor.fetchall()
if results:
print('username is taken')
else:
print("did not work")
edit* when adding this code the the rest of the program and testing i found it gives the results username taken every time, even if it is a new username. If you have any recommendations to fix this, I am open to them. I am going to continue work on this and will post results when the program is working properly.
I would like to thank you guys for your help, I did find the response I was looking for!
### check to see if user is already in database
import mysql.connector
# Database entry
mydb = mysql.connector.connect(
host='Localhost',
port='3306',
user='root',
passwd='passwd',#changed for help
database='pylogin'
)
mycursor = mydb.cursor()
user = input('username')
mycursor.execute('SELECT * FROM userpass WHERE username = username')
results = mycursor.fetchall()
if results:
print('Username is taken')
else:
print('did not work')`

python mysql (fetch whole table)

i am new to python and mysql,
i have to present a code to my office head. this code should help pull a table called "customer". I just want assistance to know if there are any errors in my code.
hostname = 'localhost'
port =
username = 'USERNAME'
password = 'PASSWORD'
database = 'DBNAME'
# Open database connection
conn = pymysql.connect(host=hostname, port=,user=username, passwd=password, db=database)
cur = conn.cursor()
cur.execute("SELECT * customer")
print(cur)
db.close()
Thanks in Advance,
Ninad.
I am using python 3.6
You may need to print
cur.fetchall()
to have your results appear

Python rowcount returning negative 1

Please can someone help i cant believe I am not getting this right. I am trying to count the number of rows that I have in a mysql db. The correct number is 7, however everytime I execute the following I get an answer of -1. The connection is established successfully.I am using python 3.4.4
import mysql.connector
config = {
'user': 'root',
'password': '',
'host': '127.0.0.1',
'database': 'test'
}
cnx =mysql.connector.MySQLConnection(**config)
if cnx.is_connected():
print('Connected to MySQL database')
cursor = cnx.cursor()
cursor.execute("SELECT * FROM test")
numrows = int (cursor.rowcount)
print(numrows)
According to the documentation:
For nonbuffered cursors, the row count cannot be known before the rows have been fetched. In this case, the number of rows is -1 immediately after query execution and is incremented as rows are fetched.
Which means that, in order for .rowcount to work in this case, you have to fetch the results first.
cursor.execute("SELECT * FROM test")
rows = cursor.fetchall()
numrows = int(cursor.rowcount)
Of course, you can also get the length of the rows list.

Error: "Unable to Open Database" using sqite3 and Windows

I'm a newbie to this, and can't figure out how to solve this error that I get when attempting to query from the database. The error reads:
rm: cannot unlink 'C:/Users/myName/Documents/GitHub/active_record_lite/lib../cats.db': Permission denied
Error: unable to open database "'C:\Users\myName\Documents\GitHub\active_record_lite'": unable to open database file
By going to "Properties" and viewing the "Security" tab, everything is checked under "Allow" for security, so I assume that the project and all subfiles have full permission (is this correct?).
I have a "cats.db" and "cats.sql" file in the project folder.
This is where I attempt to query from the database:
require_relative 'db_connection'
require 'active_support/inflector'
class SQLObject
def self.columns
cols = DBConnection.execute2(<<-SQL, #table_name)
SELECT
*
FROM
?
SQL
And here is a db_connection.rb file:
require 'sqlite3'
# https://tomafro.net/2010/01/tip-relative-paths-with-file-expand-path
ROOT_FOLDER = File.join(File.dirname(__FILE__), '..')
CATS_SQL_FILE = File.join(ROOT_FOLDER, 'cats.sql')
CATS_DB_FILE = File.join(ROOT_FOLDER, 'cats.db')
class DBConnection
def self.open(db_file_name)
#db = SQLite3::Database.new(db_file_name)
#db.results_as_hash = true
#db.type_translation = true
#db
end
def self.reset
commands = [
"rm '#{CATS_DB_FILE}'",
"cat '#{CATS_SQL_FILE}' | sqlite3 '#{CATS_DB_FILE}'"
]
commands.each { |command| `#{command}` }
DBConnection.open(CATS_DB_FILE)
end
def self.instance
reset if #db.nil?
#db
end
def self.execute(*args)
puts args[0]
instance.execute(*args)
end
def self.execute2(*args)
puts args[0]
instance.execute2(*args)
end
def self.last_insert_row_id
instance.last_insert_row_id
end
private
def initialize(db_file_name)
end
end
Any advice/suggestions welcomed! Thanks!

Groovy: how to use Exceptions or <If> <else> construction with MySQL queries?

I have a query from table of MySQL database, and i want check: have i got this number in table and if not - println that this number not in database, if this number exist - println that this number exist. How i can do that, using Exceptions or (If) (else) construction?
Assuming you're using an in memory hsql db:
def sql = Sql.newInstance( 'jdbc:hsqldb:mem:testDB', // JDBC Url
'sa', // Username
'', // Password
'org.hsqldb.jdbc.JDBCDriver') // Driver classname
def tim = 'tim'
def name = sql.firstRow( "SELECT name FROM users WHERE userid=$tim" )?.name
if( name ) {
println "Name was $name"
}
else {
println "Name not found"
}