I am trying to use a local database over my computer using "XAMPP". The module name is MySQL & Apache. Like I was indicated by a youtube video, I had to start them two. Now, my IDLE doesn't recognize MySQL, but when I wrote sqlite3, it worked, but it had no place to take the database from. What can I do for my program to accept MySQL?
Thanks.
My Code Looks Like This:
import sqlite3
print "Welcome To The Royal Bank Of The Thomean Kingdom"
db = sqlite3.connect(host = "127.0.0.1",
user = "root",
passwd = "",
db="dbpython")
query = db.cursor()
loop = 'true'
while(loop == 'true'):
username = raw_input("Username:")
password = raw_input("Password:")
if(query.execute("SELECT * FROM `USERS` WHERE `username`='" + username + "' AND `password`='" + password + "'")):
db.commit()
print "Logged In"
else:
db.commit()
print "Failure"
sqlite3 is a builtin Python module, which is why it works out of the box, and importing MySQL libraries will not
SQLite does not connect to MySQL or even remote/local network addresses and ports. The SQLite protocol and data formats are not even the same as MySQL.
You'll need to separately install a MySQL module, such as mysql-python
There's no specific reason why a local XAMPP server couldn't use SQLite and you can refer to the Python documentation for how to open / connect to a specific database file
Similarly, I see no specific reason for XAMPP here. You could use Flask or Django, and run entirely in Python, and only later add a database
Also, please don't write SQL queries using "string + string" - it allows for SQL injection attacks. The solution is to use prepared statements
Also, storing passwords directly in your database immediately after user entry (i.e in plain text) is just asking for trouble
Related
I think I'm going mad here... again :). I'm trying to do the most simple thing on the planet and it doesn't work for some reason unknown to me. I have a python script that connects to a mssql database using pypyodbc and does stuff. when I insert data into the database, it works. when I try to extract it, it fails miserably. what am I doing wrong?
import pypyodbc as mssql
msConnErr = None
try:
msconn = mssql.connect('DRIVER={SQL Server};SERVER=server_name;DATABASE=database;TRUSTED_CONNECTION=True')
print('Source server connected')
srcCursor = msconn.cursor()
except:
print('Source server error')
msConnErr = True
srcCursor.execute("SELECT * FROM schema.table")
srcResult = srcCursor.fetchall()
print(srcResult)
the connection works as I'm being given a successful message. I can also see my script using sql server management studio being connected to the correct database, so I know I'm working in the right environment. the error I'm getting is:
UndefinedTable: relation "schema.table" does not exist
LINE 1: SELECT * FROM schema.table
the table exists, I must specify the schema as I have the same table name in different schemas (data lifecycle). I can extract data from it using sql server management studio, yet python fails miserably. it doesn't fail to insert 35 million rows in it using the same driver. no other query works, even SELECT ##VERSION fails, SELECT TOP (10) * FROM schema.table fails etc. ...
any ideas?
basically, I had a piece of code that would rewrite the srcCursor variable with another connection, obviously that relation wouldn't be present on another server. apologies!
I am setting up a mysql app. This is my getUsername method connects using standard mysqldb formatting.
Does this mean it is a prepared statement? Also, is this code safe, or am I vulnerable to SQL injection?
def selectUser(userName):
try:
username = pickle.loads(base64.decode(userName))
except:
username = "admin"
query = "SELECT name FROM users WHERE name = '%s'"
conn = MySQLdb.connect('localhost', 'dbAdmin', 'lja8j30lJJal##', 'blog');
with conn:
c = conn.cursor()
c.execute(query, (username,))
No - there is no way to make a prepared statement in MySQLdb. You won't find any mysql_stmt_init(), mysql_stmt_prepare() or mysql_stmt_execute() in the MySQL API binding in _mysql.c.
For whatever reason, the author of MySQLdb chose to simulate parameters instead of using real server-side prepared statements.
To protect against SQL injection, the MySQLdb package uses Python string-format syntax. It interpolates dynamic values into SQL queries and applies correct escaping, i.e. adding \ before quote characters to make sure dynamic values don't contain string delimiters.
See my answer to How do PyMySQL prevent user from sql injection attack? for a demonstration.
However, escaping doesn't help if you need to use dynamic values for numeric constants.
I'm trying to enter data from python 3.4 into a MySQL database, with both of these entities being within pythonAnywhere. In other words, I'm writing a python 3.4 program in pythonAnywhere and need to connect to a MySQL db also within pythonAnywhere. I've checked other answers here and haven't quite figured it out. I've tried the ( -u -h -p) syntax mentioned by a few posts, but I'm not sure if that is just for gaining access from outside of pythonAnywhere.
Any help would be appreciated.
++++++++++++++++++++
Actually I figured it out (with kudos to Tony Darnell at the Scripting MySQL website, from whom I plagiarized most of this:
import MySQLdb
db=MySQLdb.connect(
host='Your_User_Name.mysql.pythonanywhere-services.com',
user='Your_User_Name',
passwd='Your_pythonAnywhere_password',
db='Your_User_Name$Your_Data_Base')
everything above starting with 'Your' refers to you personal account info with pythonanywhere
everything else gets listed exactly as shown. Watch that $ that follows your user name as part of the database name (db = etc.)
cursor = db.cursor ()
execute the SQL query using execute() method.
cursor.execute ("Enter any MySQL query here. use the quotes. no semi-colon")
fetch a single row from query using fetchone() method.
row = cursor.fetchone ()
print(row)
fetch all the rest of the query using fetchall() method
data = cursor.fetchall()
print(data)
close the cursor object
cursor.close ()
close the connection
db.close ()
I'm trying to populate a couple databases with psycopg2 within a server I am not the root user of (don't know if it's relevant or not). My code looks like
import json
from psycopg2 import connect
cors = connect(user='jungal01', dbname='course')
req = connect(user="jungal01", dbname='requirement')
core = cors.cursor()
reqs = req.cursor()
with open('gened.json') as gens:
geneds = json.load(gens)
for i in range(len(geneds)):
core.execute('''insert into course (number, description, title)
values({0}, {1}, {2});''' .format(geneds[i]["number"], geneds[i]['description'], geneds[i]['title'] ))
reqs.execute('''insert into requirement (fulfills)
values({0});''' .format(geneds[i]['fulfills'] ))
db.commit()
when I execute the code, I get the above pycopg2 error. I know that these particular databases exist, but I just can't figure out why it won't connect to my databases. (side quest, I am also unsure about that commit statement. Should it be in the for loop, or outside of it? It suppose to be database specific?)
First, you have db is not a defined variable, so you code shouldn't run completely anyway.
\list on this server is a bunch of databases full of usernames, of which my username is one
Then the following is how you should connect. To a database, not a table, and the regular pattern is to put the database name, and then the user/pass.
A "schema" is a loose term in relational database. Both tables and databases have schemas, but you seem to be expecting to connect to a table, not a database.
So, try this code with an attempt at fixing your indentation and SQL injection problem -- See this documentation
Note that you first must have created the two tables in the database you are connecting to.
import json
from psycopg2 import connect
username = 'jungal01'
conn = connect(dbname=username, user=username)
cur = conn.cursor()
with open('gened.json') as gens:
geneds = json.load(gens)
for g in geneds:
cur.execute('''insert into course (number, description, title)
values(%(number)s, %(description)s, %(title)s);''', g)
cur.execute('''insert into requirement (fulfills)
values(%(fulfills)s);''', g)
conn.commit()
Allen, you said: "in postgres, tables are databases." That's wrong. Your error message results from this misunderstanding. You want to connect to a database, and insert into a table that exists in that database. You're trying to insert into a database -- a nonsensical operation.
Make sure you are giving the catalog name as database name and not the schema's under catalog.
Catalog is confusing and quite unnecessary. More details below: What's the difference between a catalog and a schema in a relational database?
Never use python before, here want to using procedure already written in SQL server Script, then write a python application connect to database (already connected) rather than JAVA, because this is much easier.
Let user to give an input as the #Departments, then calculate the average of that Department's average salary.
My sql server procedure code:
CREATE PROC aaatest # Departments varchar(40)
AS
BEGIN
SELECT AVG(P.Salary)
FROM Company P
WHERE P.Department = #Departments
END
please write the a python application to get the input then pass to the #Departments. (conn = pymssql ... is already done!)
I guess this should give you some hint of how to script your requirement:
import pyodbc
cnxn=pyodbc.connect(r'Driver={SQL Server};Server=<servername>;Trusted_Connection;user=<username>;password=<password>',autocommit = True)
cursor=cnxn.cursor()
department=raw_input('Enter department:')
query='EXEC [master].[dbo].[aaatest] '+department+''
cursor.execute(query)
cnxn.close()