Create table: #Import
database
import pymysql
def createtable():
conn=pymysql.connect("localhost","root","123456","myschool") #建立连接
mycursor=conn.cursor() #Get the cursor object
sqlstr='''
create table test(
id int primary key auto_increment,
name varchar(20) not null,
sex char(2)
)default charset utf8;'''
mycursor.execute(sqlstr) #Execute SQL statement
conn.close()#Close the connection object
createtable()
Insert content:
def inserttable():
conn1=pymysql.connect("localhost","root","123456","myschool")#establish a connection
mycursor1=conn1.cursor()
sql2='''insert into test(name,sex) values('Li Miao','female')'''
try:
result=mycursor1.execute(sql2)
print(result)
conn1.commit()
except:
conn1.rollback()
conn1.close()
inserttable()
encapsulates the method of connecting to the database:
def getconn():
conn=pymysql.connect("localhost","root","123456","myschool") #establish a connection
mycursor=conn.cursor( ) #Get the cursor object
return [conn,mycursor]
delete
def deltable():
conn=getconn()
sqlstr='''delete from test where id=1'''
try:
print(conn[1].execute(sqlstr) )
conn[0].commit()
except:
conn[0].rollback()
conn[0].close()
deltable()
change:
def updatetable():
conn=getconn()
sqlstr='''update test set name='Liu Chao' where id=2 '''
try:
print(conn[1].execute(sqlstr))
conn[0].commit()
except:
conn[0].rollback()
conn[0].close()
updatetable()
encapsulation method, single write SQL statement:
def operationtable(sqlstr):
conn=getconn()
try:
print(conn[1].execute(sqlstr))
conn[0].commit()
except:
conn[0].rollback()
conn[0].close()
sqlstr='''delete from test where name=" Zhang San"'''
sqlstr='''insert into test(name,sex) values("Yang Naiwen","male")'''
sqlstr=''' update test set name="Zhou Zhou" where id=6 '''
operationtable(sqlstr)# Pass the SQL statement into the
query (encapsulation)
class Test():
def __init__(self,id=None,name=None,sex=None):
self.id=id
self.name =name
self.sex=sex
def __str__(self):
return "id:"+str(self.id)+",name:"+self.name+",sex:"+self.sex
#Query
def querytable():
list=[]
conn=getconn() #Call the public connection method
sqlstr='''select id,name,sex from test''' #Query content
conn[1].execute(sqlstr) #Execute SQLstr
rs =conn[1].fetchall() #rs is the returned result, which is a tuple
for row in rs:
test=Test(row[0],row[1],row[2])#Call the above method, Generated object
list.append(test)#Add object to list#
print("id:%d,name:%s,sex:%s"%(row[0],row[1],row[2] ))#traverse the output result
conn[0].close()#close
return list#return list
testlist=querytable()
for row in testlist:
print(row)#row overrides str
PyMySQL is a library for connecting to MySQL servers in Python 3.x, and mysqldb in Python 2.
PyMySQL follows the Python Database API v2.0 specification and includes the pure-Python MySQL client library.
PyMySQL download address: https://github.com/PyMySQL/PyMySQL.
Enter in cmd or enter in the terminal in pycharm: pip install PyMySQL to install
environment variables: the path with bin
can be in the Python environment, right-shift to open the window and enter: pip install PyMySQL Note: It is best to use pip3
PyMysql operation: 1. Import PyMySQL module 2. Establish connection Conn=pymysql.connect("localhost","root","123456","myschool") 3. Get cursor object 4. Write SQL statement 5. Execute SQL statement mycursor.execute(sqlstr) 6. Close the connection conn.close() 7. create returns 1 or 0 8. select returns a virtual table Python query Mysql uses the fetchone() method to obtain a single piece of data, and the fetchall() method to obtain multiple pieces of data. fetchone(): This method fetches the next query result set. The result set is an object fetchall():
rowcount: This is a read-only property and returns the number of rows affected by the execute() method.
Notes for connecting to the database:
1. The data and table have been created
2. The user name and password for connecting to the database
cursor.execute('select varsion()') call execute to execute the SQL query, and return the version number
** to get the execution result. If the table is created The statement returns none
*** garbled code: 1 change in the original code; 2 add charset='utf8' after the connection; 3 when creating the table, follow the default charset utf8.