Skip to main content

Posts

PYTHON MYSQL WHERE

M YSQL WHERE Select With a Filter When selecting records from a table, you can filter the selection by using the "WHERE" statement: import mysql.connector mydb = mysql.connector.connect(   host="localhost",   user="myusername",   password="mypassword",   database="mydatabase" ) mycursor = mydb.cursor() sql = "SELECT * FROM customers WHERE address = 'Park Lane 38'" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult:  print(x) sql = "SELECT * FROM customers WHERE address Like '%way%'" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x) mycursor.close() mydb.close() (11, 'Ben', 'Park Lane 38') (1, 'John', 'Highway 21') (9, 'Susan', 'One way 98') (14, 'Viola', 'Sideway 1633') Prevent SQL Injection W hen query values are provided by t

PYTHON MYSQL SELECT

M YSQL SELECT Select From a Table To select from a table in MySQL, use the "SELECT" statement: import mysql.connector mydb = mysql.connector.connect(   host="localhost",   user="myusername",   password="mypassword",   database="mydatabase" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchall() for x in myresult:   print(x) mycursor.execute("SELECT name, address FROM customers") myresult = mycursor.fetchall() for x in myresult:    print(x) mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchone() print(myresult) mycursor.close() mydb.close() (1, 'John', 'Highway 21') (2, 'Peter', 'Lowstreet 27') (3, 'Amy', 'Apple st 652') (4, 'Hannah', 'Mountain 21') (5, 'Michael', 'Valley 345') (6, 'Sandy', 'Ocea

PYTHON FILE HANDLING, CREATE-WRITE-READ-REMOVE FILES

F ILE HANDLING, CREATE-WRITE-READ-REMOVE FILES File Handling The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file: "r" - Read - Default value. Opens a file for reading, error if the file does not exis t "a" - Append - Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing, creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file exists In addition you can specify if the file should be handled as binary or text mod e "t" - Text - Default value. Text mode "b" - Binary - Binary mode (e.g. images) Open a File To open the file, use the built-in open() function. The open() function returns a file object, which has a read() method for reading the content of the fil

PYTHON MYSQL INSERT

M YSQL INSERT INTO TABLE Insert Into Table Notice the statement: mydb.commit(). It is required to make the changes, otherwise no changes are made to the table. import mysql.connector mydb = mysql.connector.connect(   host="localhost",   user="yourusername",   password="yourpassword",   database="mydatabase" ) mycursor = mydb.cursor() sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" val = ("John", "Highway 21") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.") 1 record inserted. Insert Multiple Rows To insert multiple rows into a table, use the executemany() method. The second parameter of the executemany() method is a list of tuples, containing the data you want to insert: import mysql.connector mydb = mysql.connector.connect(   host="localhost",   user="yourusername",   password="yourpas

PYTHON MYSQL CREATE DATABASE & TABLE

M YSQL CREATE DATABASE & TABLE You should have MySQL installed on your computer. Python needs a MySQL driver to access the MySQL database. We recommend that you use PIP to install "MySQL Connector". Create Connection import mysql.connector mydb = mysql.connector.connect(   host="localhost",   user="yourusername",   password="yourpassword" ) print(mydb) <mysql.connector.connection.MySQLConnection object ar 0x016645F0> Creating a Database import mysql.connector mydb = mysql.connector.connect(   host="localhost",   user="yourusername",   password="yourpassword" ) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE mydatabase") Check if Database Exists import mysql.connector mydb = mysql.connector.connect(   host="localhost",   user="yourusername",   password="yourpassword" ) mycursor = mydb.cursor() mycurso

PYTHON STRING FORMATTING

S TRING FORMATTING quantity = 3 itemno = 567 price = 49 myorder = "I want {} pieces of item number {} for {:.2f} dollars." print(myorder.format(quantity, itemno, price)) I want 3 pieces of item number 567 for 49.00 dollars. myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars." print(myorder.format(quantity, itemno, price)) I want 3 pieces of item number 567 for 49.00 dollars. age = 36 name = "John" txt = "His name is {1}. {1} is {0} years old." print(txt.format(age, name)) His name is John. John is 36 years old. myorder = "I have a {carname}, it is a {model}." print(myorder.format(carname = "Ford", model = "Mustang")) I have a Ford, it is a Mustang.

PYTHON TRY...EXCEPT

T RY...EXCEPT try:   f = open("demofile.txt")   try:     f.write("Lorum Ipsum")   except:     print("Something went wrong when writing to the file")   finally:     f.close() except:   print("Something went wrong when opening the file") Something went wrong when writing to the file x = "hello" if not type(x) is int:   raise TypeError("Only integers are allowed") Traceback (most recent call last):   File "/usr/lib/python3.8/idlelib/run.py", line 559, in runcode     exec(code, self.locals)   File "/home/kartik/Downloads/tryCatch.py", line 16, in <module>     raise TypeError("Only integers are allowed") TypeError: Only integers are allowed