PYTHON - MYSQL CONNECTIVITY
To download MYSQL V5.7 CLICK HERE
To download connector via pip;
python -m pip install mysql-connector
Establishing connection :
Import mysql.connector as m
Mydb=m.Connect(host="localhost",user="root",passwd="your_mqsql_password")
If print(Mydb) doesn't show any error then it means that the connection has been successfully made
All the below commands need to written after the above commands which create a connection
Note:Alternate of localhost is 127.0.0.0
Alternate representation :
<<1>>-host, <<2>>-user, <<3>> password
Creating database:
mycursor.execute("create database datbase_name")
If database already exits then it create an error
To check if connected use : mydb.is_connected()
To access a database :
Method 1 : Same connection with a command an additional command at top mycursor.execute("use database_name")
Or
Method 2: The following modifications in connection
Mydb=m.Connect(host="localhost",user="root",passwd="your_mqsql_password", database= "database_name")
Displaying tables:
for x in mycursor :
print(x)
In above command x be a single element tuple containing name of a table in selected database
All mysql need to be written as : mycursor.execute("mysql_command")
Important points to keep in mind while using execute:
1.)The mysql_command should not contain " ie double inverted comma and can only contain ' ie single inverted commas without semicolon or use triple quotes outside with semicolon
2.)To print some result of command like show, desc use following loop after execute:
print(x)
Here x will be a tuple with its element contains result of 1 single row of the mysql_command
3.) With commands insert, delete and update after execute we need to write:
Mydb.commit()
to save the changes in the table
4.) To display records using select we need to use the fetch command family after execute:
myrecords=mycursor.fetchall()
for x in myrecords:
print(x)
Here x will be a tuple with its element contains result of 1 single row of the query
The various fetch commands are as follows and have the same function as their name:
fetchone()
fetchmany(n)
5.) mycursor.rowcount is a variable which stores the number of records affected by the most recent mycursor.execute command
6.) To print error use the execute statement in the try block and in the except block use:
Mydb.rollback()
To prevent any unwanted or incomplete changes in the database
7.) To print structure of table:
for j in mycursor:
print(j)
Comments
Post a Comment
For any queries or suggestions
Comment Here