Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
First time with mysql
#6
Of course you must first have a MySQL database and in that database a table.

My table names look like: allstudentsAnswers20BE

host is the ip of the remote or local server: host='123.456.789.123'
user is your user name in the that database: user='my_username'
password is the password for this user on that database: password = 'my_database_password',
db is the name of the database you want to access: db='my_database_name'

I have several different classes of students and each class has a table.

I need to collect the data in the 2 columns studentnr and score and write them to a dictionary.

So I pass clas and weeknr to the function below and it works just like magic!

So fast, if you blink, you missed it.

def mysqlRemoteCW(clas, weeknr): 
        # To connect remote MySQL database 
        conn = pymysql.connect( 
            host='123.456.789.123', 
            user='my_username',  
            password = 'my_database_password', 
            db='my_database_name', 
            ) 
          
        cur = conn.cursor()
    
        # Select query 
        #cur.execute(f"SELECT studentnr, score FROM allstudentsAnswers{clas} WHERE weeknr = '{weeknr}'")
        #cursor.execute("SELECT spam FROM eggs WHERE lumberjack = ?", (lumberjack,))
        sql = f"SELECT studentnr, score FROM allstudentsAnswers{clas}CW WHERE weeknr = %s"
        cur.execute(sql, (weeknr,))
        output = cur.fetchall() 
          
        #for i in output: 
            #print(i) 
          
        # To close the connection 
        conn.close()
        return output

results = mysqlRemoteCW(clas, weeknr)
# now put results in a dictionary
And yeah, work through a tutorial. MySQL takes some getting used to.

Good Luck!
Reply


Messages In This Thread
First time with mysql - by pascal111 - Sep-24-2021, 08:12 PM
RE: First time with mysql - by bowlofred - Sep-24-2021, 08:19 PM
RE: First time with mysql - by pascal111 - Sep-24-2021, 08:24 PM
RE: First time with mysql - by bowlofred - Sep-24-2021, 09:03 PM
RE: First time with mysql - by deanhystad - Sep-24-2021, 08:51 PM
RE: First time with mysql - by Pedroski55 - Sep-25-2021, 07:45 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Mysql and mysql.connector error lostintime 2 764 Oct-03-2023, 10:25 PM
Last Post: lostintime
  Mysql error message: Lost connection to MySQL server during query tomtom 6 16,460 Feb-09-2022, 09:55 AM
Last Post: ibreeden
  Hard time trying to have clean MySQL to CSV program PierreSoulier 2 2,830 Jul-20-2018, 07:52 AM
Last Post: PierreSoulier

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020