windows下python3.6连接mysql数据库

pymysql支持python3.6

通过pip安装pymysql:

进入python根目录Scrips目录下

pip install pymysql
pymysql自动安装完成

示例代码:


    
    
  1. # -*- coding: UTF-8 -*-
  2. import pymysql
  3. import pymysql.cursors
  4. connection = pymysql.connect(host= 'localhost',
  5. user= 'root',
  6. password= 'root',
  7. db= 'test',
  8. port= 3306,
  9. charset= 'utf8') #注意是utf8不是utf-8
  10. try:
  11. with connection.cursor() as cursor:
  12. sql_1 = 'select * from student'
  13. cout_1=cursor.execute(sql_1)
  14. print( "数量: "+str(cout_1))
  15. for row in cursor.fetchall():
  16. print( "id:",str(row[ 0]), 'name',str(row[ 1]), 'age',str(row[ 2]))
  17. sql_2 = 'insert into student(name,age,sex) value("田晓霞",26,"男")'
  18. cout_2=cursor.execute(sql_2)
  19. print( "数量: "+str(cout_2))
  20. connection.commit()
  21. finally:
  22. connection.close()

注意:

connection 连接设置编码是utf8,而不是utf-8


pymysql支持python3.6

通过pip安装pymysql:

进入python根目录Scrips目录下

pip install pymysql
pymysql自动安装完成

示例代码:


  
  
  1. # -*- coding: UTF-8 -*-
  2. import pymysql
  3. import pymysql.cursors
  4. connection = pymysql.connect(host= 'localhost',
  5. user= 'root',
  6. password= 'root',
  7. db= 'test',
  8. port= 3306,
  9. charset= 'utf8') #注意是utf8不是utf-8
  10. try:
  11. with connection.cursor() as cursor:
  12. sql_1 = 'select * from student'
  13. cout_1=cursor.execute(sql_1)
  14. print( "数量: "+str(cout_1))
  15. for row in cursor.fetchall():
  16. print( "id:",str(row[ 0]), 'name',str(row[ 1]), 'age',str(row[ 2]))
  17. sql_2 = 'insert into student(name,age,sex) value("田晓霞",26,"男")'
  18. cout_2=cursor.execute(sql_2)
  19. print( "数量: "+str(cout_2))
  20. connection.commit()
  21. finally:
  22. connection.close()

注意:

connection 连接设置编码是utf8,而不是utf-8


猜你喜欢

转载自blog.csdn.net/piyongduo3393/article/details/88140270