標籤:
一、mysql基礎:
1.資料類型:
1)數字類型:
整數: tinyint、smallint、mediumint、int、bigint
浮點數: float、double、real、decimal
2)日期和時間: date、time、datetime、timestamp、year
3)字串類型:
字串: char、varchar
文本: tinytext、text、mediumtext、longtext
二進位(可用來儲存圖片、音樂等): tinyblob、blob、mediumblob、longblob
2.一些命令:
1)mysql -h 主機名稱 -u 使用者名稱 -p 遠程登入加-h
2)create database 資料庫名 [其他選項]; eg:create database samp_db character set gbk;
3)show databases; 查看有哪些資料庫
4)mysql -D 所選擇的資料庫名 -h 主機名稱 -u 使用者名稱 -p
5) use 資料庫名;切換資料庫
6)create table 表名稱(列聲明);
eg: create table students (
id int unsigned not null auto_increment primary key,
name char(8) not null,
sex char(4) not null,
age tinyint unsigned not null,
tel char(13) null default "-"
);
可以通過任何文字編輯器將語句輸入好後儲存為 createtable.sql 的檔案中, 通過命令提示字元下的檔案重新導向執行執行該指令碼。
開啟命令提示字元, 輸入: mysql -D samp_db -u root -p < createtable.sql
7)create table tablename(columns)
8)describe 表名; 命令可查看已建立的表的詳細資料。
9)insert [into] 表名 [(列名1, 列名2, 列名3, ...)] values (值1, 值2, 值3, ...);
10)select 列名稱 from 表名稱 [查詢條件];
11)where 關鍵詞用於指定查詢條件, 用法形式為: select 列名稱 from 表名稱 where 條件;
12)update 表名稱 set 列名稱=新值 where 更新條件;
13)delete from 表名稱 where 刪除條件;不加where表示清空表中所有的內容,和TRUNCATE [TABLE] tbl_name一樣
14)添加列:alter table 表名 add 列名 列資料類型 [after 插入位置];
15)修改列:alter table 表名 change 列名稱 列新名稱 新資料類型;
16)刪除列:alter table 表名 rename 新表名;
17)刪除庫:drop database 資料庫名;
18)drop table命令用於刪除資料表。
19)mysqladmin -u root -p password 新密碼
二、python操作mysql
1 import MySQLdb2 db=MySQLdb.connect(‘localhost‘,‘root‘,‘*****‘,‘students‘)3 cursor = db.cursor()4 cursor.execute("SELECT VERSION()")5 data = cursor.fetchone()6 print "Database version : %s " % data7 db.close()
1 import MySQLdb 2 db = MySQLdb.connect("localhost","root","*****","students" ) 3 cursor = db.cursor() 4 sql = """INSERT INTO student(NAME,AGE, SEX, INCOME) 5 VALUES (‘Mac‘, 20, ‘M‘, 2000)""" 6 try: 7 cursor.execute(sql) 8 db.commit() 9 except:10 db.rollback()11 db.close()
必須執行 db.commit()函數提交操作結果。
python操作mysql