zoukankan      html  css  js  c++  java
  • python操作mysql

    功能:通过python操作mysql数据库

    1.安装MySQL-python

    要想使python可以操作mysql 就需要MySQL-python驱动,它是python 操作mysql必不可少的模块。

    下载地址:https://pypi.python.org/pypi/MySQL-python/

    下载后安装就行了

    检测是否安装通过import MySQLdb查看,如何没有安装成功,就会报错。

    安装成功,导入没有提示的。

    2.MYSQ的基本操作

    回顾下mysql基本操作

    0.产看mysql信息                    status;
    1.整个命令写错                                  可以在后面输入 c 取消执行
    2.单行命令写错                                  可以按esc键清除某行
    3.给某个数据库创建单独管理员和密码        grant all on houdunwang.* to "hdw"@"localhost" identified by "hdw";
    4.创建数据库                                    cerate database houdunwang;
                            create database hd default character set utf8;//指定字符集
    5.删除数据库                    drop database houdunwang;
    6.创建数据表                    create table students(id int(10) primary key auto_increment,name varchar(30),age tinyint(2));
                            create table user(id int(10) unsigned primary key auto_increment,name varchar(60),age tinyint(2)) default character
                            set utf8;//指定字符集
    
    7.查看所有数据表                show tables;
    8.查看指定数据表                desc students;
    
    9.增                        insert into students (name,age) values("zhansan",22);
    
    
    10.导出数据库(先退出数据库)            C:UsersAdmin>mysqldump -uroot -p houdunwang>d:/houdunwang.sql    
    11.删除数据表                    drop table students;
    12.导入数据库                    C:UsersAdmin>mysql -uroot -p houdunwang < d:/houdunwang.sql
    13.执行外部的sql语句(先选择一个数据库)    source d:/houdunwang.sql;

    3.通过python操作

    数据库中写入数据
    import
    MySQLdb conn = MySQLdb.connect("localhost","root","root","hd") #连接数据库 cur=conn.cursor()  #创建游标 cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))") cur.execute("insert into student values('2','Tom','3 year 2 class','9')") cur.close() conn.commit() conn.close()

    数据库中遍历数据
    import
    MySQLdb conn = MySQLdb.connect("localhost","root","root","hd") cur=conn.cursor() #cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))") #cur.execute("insert into student values('2','Tom','3 year 2 class','9')") res=cur.execute("select * from student") print res info = cur.fetchmany(res) for i in info: print i cur.close() conn.commit() conn.close()

  • 相关阅读:
    解决express不是内部或外部命令
    spring ioc认识
    Filter编码过滤
    call、apply、bind
    js面向对象浅析
    由clientWidth到document
    401
    删除页面中Form下面隐藏的ViewStatue
    asp.net 下载
    day98
  • 原文地址:https://www.cnblogs.com/cui0x01/p/6223981.html
Copyright © 2011-2022 走看看