Skip to main content

Posts

Showing posts from September 4, 2022

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