启动mysql
MacBook-Air:~ huangyong$ brew services start mysql
登陆mysql
mysql -uroot
查看数据库
mysql> show databases;
创建数据库huang
mysql> create database huang;
使用huang
mysql> use huang;
查看表
mysql> show tables;
Empty set (0.00 sec)
创建表stu
mysql> create table stu(id int,
-> name varchar(20),
-> sex char(1),
-> age int);
查看表stu
mysql> show tables;
+-----------------+
| Tables_in_huang |
+-----------------+
| stu |
+-----------------+
1 row in set (0.00 sec)
查看表结构
mysql> desc stu;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(20) | YES | | NULL | |
| sex | char(1) | YES | | NULL | |
| age | int(11) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
4 rows in set (0.01 sec)
插入数据
注意:数值是在后面的,而不是我潜意识里记得的mysql> insert into stu(123,'zhao','m',20);
mysql> insert into stu (id,name,sex,age) values (123,'zhao','m',20);
Query OK, 1 row affected (0.00 sec)
在python中的操作
import MySQLdb
这次import没任何警告提示了
连接
>>> db = MySQLdb.connect('localhost','root','','huang')
操作游标
>>> cursor = db.cursor()
要执行语句
>>> sql = '''insert into stu (id,name,sex,age) values (125,'li','w',23) '''
执行
>>> cursor.execute(sql)
提交
>>> db.commit()
关闭
>>> db.close()
循环
>>> sql = '''insert into stu (id,name,sex,age) values (125,'li','w',23) '''
>>> cursor.execute(sql)
可以插入多条,
最后>>> db.commit()一下