import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="ram1234",
database="ramesh"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
-----------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="ram1234",
database="ramesh"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT name, address FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
---------------------
Using the fetchone() Method
If you are only interested in one row, you can use the fetchone() method.
The fetchone() method will return the first row of the result:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="ram1234",
database="ramesh"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
print(myresult)
------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="ram1234",
database="ramesh"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address LIKE '%way%'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
------------------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="ram1234",
database="ramesh"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers ORDER BY name DESC"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
---------------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="ram1234",
database="ramesh"
)
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE name = 'ram1'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="ram1234",
database="ramesh"
)
mycursor = mydb.cursor()
sql = "DROP TABLE customers"
mycursor.execute(sql)
-------------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="ram1234",
database="ramesh"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
No comments:
Post a Comment
Note: only a member of this blog may post a comment.