操作mysql数据库

https://blog.csdn.net/kongsuhongbaby/article/details/84948205

  1. #!/usr/bin/python3  
  2. import pymysql   #pip install mysql-connector-python PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。
  3. #如果安装mysqldb pip install mysql 出错(C++啥的那个错误),可以直接下载whl文件:https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python 
  4. import types  
  5.   
  6. db=pymysql.connect("localhost","root","123456","python");  
  7.   
  8. cursor=db.cursor()  
  9.   
  10. #创建user表  
  11. cursor.execute("drop table if exists user")  
  12. sql="""CREATE TABLE IF NOT EXISTS `user` ( 
  13.       `id` int(11) NOT NULL AUTO_INCREMENT, 
  14.       `name` varchar(255) NOT NULL, 
  15.       `age` int(11) NOT NULL, 
  16.       PRIMARY KEY (`id`) 
  17.     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"""  
  18.   
  19. cursor.execute(sql)  
  20.   
  21.   
  22. #user插入数据  
  23. sql="""INSERT INTO `user` (`name`, `age`) VALUES 
  24. ('test1', 1), 
  25. ('test2', 2), 
  26. ('test3', 3), 
  27. ('test4', 4), 
  28. ('test5', 5), 
  29. ('test6', 6);"""  
变量的写法:
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES (’%s‘, ‘%s‘, ‘%s‘, ‘%s‘, %d )" % \ ('Mac', 'Mohan', 20, 'M', 2000) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # 发生错误时回滚 db.rollback()

 

  1.   
  2. try:  
  3.    # 执行sql语句  
  4.    cursor.execute(sql)  
  5.    # 提交到数据库执行  
  6.    db.commit()  
  7. except:  
  8.    # 如果发生错误则回滚  
  9.    db.rollback()  
  10.      
  11.      
  12. #更新  
  13. id=1  
  14. sql="update user set age=100 where id='%s'" % (id)  
  15. try:  
  16.     cursor.execute(sql)  
  17.     db.commit()  
  18. except:  
  19.     db.rollback()  
  20.       
  21. #删除  
  22. id=2  
  23. sql="delete from user where id='%s'" % (id)  
  24. try:  
  25.     cursor.execute(sql)  
  26.     db.commit()  
  27. except:  
  28.     db.rollback()  
  29.       
  30.       
  31. #查询  
  32. cursor.execute("select * from user")  
  33.   
  34. results=cursor.fetchall()  
  35.   
  36. for row in results:  
  37.     name=row[0]  
  38.     age=row[1]  
  39.     #print(type(row[1])) #打印变量类型 <class 'str'>  
  40.   
  41.     print ("name=%s,age=%s" % \  
  42.              (age, name)) 
posted @ 2020-04-26 14:25  modentime  阅读(137)  评论(0编辑  收藏  举报