Database activities in Python

Total Post:113

Points:791
 168  View(s)
Ratings:
Rate this:

how to Create, delete, select, insert, ordered by activities of SQL in Python ?

  1. Post:140

    Points:984
    Re: Database activities in Python

    Database Activities  :

    Creating a Table :

    import mysql.connector 
    mydb = mysql.connector.connect(
      host="localhost",
      user="yourusername",
      passwd="yourpassword",
      database: "mydatabase"
    )
    mycursor = mydb.cursor()
    mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")


    Insert Into Table:

    import mysql.connector 
    mydb = mysql.connector.connect(
      host="localhost",
      user="yourusername",
      passwd="yourpassword",
      database="mydatabase"
    )
    mycursor = mydb.cursor()
    sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
    val = ("mindstick", "Allahabad")
    mycursor.execute(sql, val)
    mydb.commit()
    print(mycursor.rowsaffected, "record inserted.")

    Python MySQL Select From:

    import mysql.connector 
    mydb = mysql.connector.connect(
      host="localhost",
      user="yourusername",
      passwd="yourpassword",
      database="mydatabase"
    )
    mycursor = mydb.cursor()
    mycursor.execute("SELECT * FROM customers")
    myresult = mycursor.fetchall()
    for x in myresult:
      print(x)

    Python MySQL Order By:

    import mysql.connector 
    mydb = mysql.connector.connect(
      host="localhost",
      user="yourusername",
      passwd="yourpassword",
      database="mydatabase"
    )
    mycursor = mydb.cursor()
    sql = "SELECT * FROM customers ORDER BY name"
    mycursor.execute(sql)
    myresult = mycursor.fetchall()
    for x in myresult:
      print(x)

    Delete Record: 

    import mysql.connector 
    mydb = mysql.connector.connect(
      host="localhost",
      user="yourusername",
      passwd="yourpassword",
      database="mydatabase"
    )
    mycursor = mydb.cursor()
    sql = "DELETE FROM customers WHERE address = 'Tashkhand marg'"
    mycursor.execute(sql)
    mydb.commit()
    print(mycursor.rowcount, "record(s) deleted")

Answer