mysql 操做

<?php
1,鏈接數據庫
mysql -h localhost -u root -p
password:

修改數據庫密碼:
一:
  mysqladmin -u root -p password 新密碼
  Enter password:原密碼
二:
  REPLACE INTO mysql.user (Host,User,Password)
  VALUES(%,用戶,PASSWORD(密碼));

FLUSH PRIVILEGES    刷新權限或者重啓
2,數據庫的操作
create database 數據庫表名;	             數據庫名稱
drop database 數據庫表名;		      數據庫名
show databases;		                   顯示數據庫
use 			                                數據庫名稱

3,表操作
	show tables;		                                                         顯示所有表
	desc 表名		                                                                顯示錶的結構
	drop table 表名		                                                          刪除表(有索引的時候不允許刪除)
      delete from 表名                                                                刪除表
	show create table  數據表名;		                                 顯示創建表語句
      show index from 表名;                                                    顯示一個數據表的所有索引
      optimize table 表名                                                             清理碎片
      truncate table 表名;                                                          清空表。比delete效率高。

創建表
#  若遇系統關鍵字做字段 用 反引號(tab鍵與1旁邊的鍵)
drop table if exists 表名;    #存在此表就刪除
create table 表名 (
id int(11) unsigned not null auto_increment,  # unsigned 要寫在not null 的前面
字段 decimal(10,2) not null comment '商品價格',
字段 varchar(30) not null comment '',
字段 char(32) not null comment '',
字段 smallint not null comment '',
字段 mediumint not null commment '中等的',
字段 tinyint not null comment '',
字段 enum(0,1,2) not null comment '枚舉',
字段 date not null comment '時間格式就是 1970-01-01',
字段 text not null comment '文本類型',
字段 datetime not null comment '事件類型',
字段 blob not null comment '二進制類型',
  primary key (`id`),         //主鍵  括號裏面的用反引號不會出錯。
  key `name` (`name`)     //創建index索引,搜索更快。
  )engine=InnoDB charset=utf8 collate utf8_general_ci;
engine=MyISAM
 TYPE=InnoDB 也是可以的。
 
字段的數據類型
  數值 tinyint int float double decimal(10,2) smallint
  字符串 char varchar text
  時間和日期 date datetime  通常使用int存儲時間戳
  null
  zerofill 前補0
  
//-------------------------------------------------------------
級聯完整性,一個表的數據處理另一個表的數據也自動處理 ,    engine=InnoDB   類型。
create table type( id int(11) unsigned not null auto_increment parimary key); 

create table attribute(
    #   未測試主鍵可不可以做外鍵
    type_id smallint unsigned not null comment '類型',
     foreign key (type_id[]) references type(id) on delete cascade,   #數據庫級聯完整性  # 外鍵
     key type_id(type_id),  #外鍵索引
        #     type(id) on delete  |||  on update   
        #  cascade  |||   restrict[不刪]  |||   set null ||| no Action [什麼也不幹],                              
);




//--------------------------------------------------------
4,數據操作:
    查詢        
                    select * from 表名; //查詢表中的所欲數據
                    select count(*) from 表名;  //統計表中有多少條數據
                    //order by 排序 默認asc 正序        desc 倒序
                   select * from 表名 where 條件  order by  字段1 desc,字段2 asc  //where條件排序。
                   select * from 表名 order by 字段1 asc,字段2 desc,字段3 desc
                     //   like匹配,兩邊是單引號,_一次 %任意次 not like不匹配
                    select * from user where name like '%aa%'; 
                      select * from 表名 where 1(隨便一個數字就是查詢所有的   或者一個空的字符串‘’)and like '{%aa%}';         查詢所有的數據。   //搜索詞分頁使用。
                      //   子查詢   子查詢中返回的結果不能使集合,而是一行結果。使用最多的是 in
                    select * from 表一 where 字段=(select 字段 from 表二 where 字段=值);
                    select * from 表一 where 字段 in (select 字段 from 表二 where 字段=值); 
                    // 多表查詢  as語句不容易混字段。where條件是避免出現笛卡爾乘積出現。
                    //複合條件查詢就是where有多個條件用 and 鏈接。
                    select 別名1.字段,別名2.字段 from 表一 別名1,表二 別名2 where 別名1.字段=別名2.字段。
                    //limit 數字:取幾條數據     limit 數字1,數字2:數1是偏移量   數2是條數   
                     select * from 表名  where  條件  limit offset,pagesize;//分頁   limit 數字  取幾條數據。
                    // group by 分組    字段1,字段2 可以用*代替         having  分組後在繼續排序
                     select 字段1,字段2 from 表名 group by 字段
                     select 字段1,字段2 from 表名 group by 字段 having 字段 <=> 值;
                     //In查詢
                     select 字段 from 表名 where 字段 in(1,2,3,4);
                   
    更新  	
                    update 表名  set  字段名='值',字段名='值' where 條件(=   <     >);
    插入:
                    insert into 表名(字段1,字段2)values('值1','值2');
                    把表的數據查出來再插入到表中。
                    insert into 表名(字段1,字段2) select 對應的字段名 from 表名2 where 條件 limit 條數;
    刪除:
                    delete from 表名 where 條件(=   <     >);
    授權:	
                    // 所有都可以訪問的形式
                    grant select,insert,update,delete on *.* to 用戶名@"%" Identified by "密碼";
                    // grant select,insert,update,delete on book.* to lingsi@"%" Identified by "abc123"; 
                    // 限定的形式,localhost ,127.0.0.1
                    grant select,insert,update,delete on book.* to 用戶名@限定(127.0.0.1 || localhost) Identified by "密碼";
                    // grant select,insert,update,delete on book.* to 用戶名@localhost Identified by "123456"; 
1,修改字段:

   alter table 數據表名   change 原字段名 新字段名 類型  屬性 索引;	change比modify強
   alter table 數據表名  modify 字段名 類型 屬性 索引;

   alter table 數據表名  add 字段名 類型  屬性 索引;
   alter table 表名 add 字段 int(11) not null default 0;

   alter table 數據表名 drop  字段名;

   alter table 原數據表名 rename as 新表名;       給表重新命名

   alter table 表名 engine = InnoDB;       修改表引擎

   alter table goods_cat add index(`字段`);
3,索引的操作
   alter table 表名 add  index/unique/  索引名稱(字段)
   alter table 表名 add  primary key(字段)
   alter table 表名 drop  index/unique 索引名稱;
   show indexes from 表名;
  	 PRIMARY, INDEX, UNIQUE 這3種是一類
	PRIMARY 主鍵。 就是 唯一 且 不能爲空。
	INDEX 索引,普通的,加快速度
	UNIQUE 唯一索引。 不允許有重複。
	FULLTEXT 是全文索引,用於在一篇文章中,檢索文本信息的。對中文支持不好,不用
      key   還有複合索引

inner jion       left join       right jion       outer jion           full join


擴展:
數據庫備份:
mysqldump -h localhost -u root -p 數據庫名>物理路徑\文件名(c:123.sql);

導入備份數據
//-p  密碼 -u 用戶 -h 主機  --opt -d 表結構  -t只有數據
mysql -h localhost -u root -p 數據庫名<物理路徑\文件名;//到處數據和表結構
mysqldump --opt -d 數據庫 -u root >c:12.sql; //導出表結構 --opt -d

As別名的用法,字段名之間用  (別名.字段名)  得到別名用   (表名as別名)as可以省略   
select 別名.name,別名.age from 表名 別名;

distinct關鍵字,使用select語句去除結果中重複的記錄。只返回一個。默認爲 All 不用寫。
select dietinct 字段名 from 表名。

查詢版本,select version();
數值計算,select 10*10;
普通連寫方式,select version(),10+10;
as連寫,select version() MYSQL_VERSION,10*10 EXPRESSION;

order by用法:
排序查詢:將查詢到的結果按照指定字段順序排序,如果第一個字段不能排列出順序先後,就會按照後一個字段進行排序

describe 表名 ,顯示錶結構。


次數統計
count() count(*) count(字段)

求和    sum()
平均數     avg()
最大值   max()
最小值     min()
字段的拼接   concat()  如 update user set name=concat(name,id);  name名是name+id
版本號     version()


mysql  常用函數
mysql_connect('localhost','root','密碼');
mysql_pconnect();     長連接。
mysql_affected_rows()     取得前一次mysql操作鎖影響的行數
mysql_errno() — 返回上一個 MySQL 操作中的錯誤信息的數字編碼
mysql_error() — 返回上一個 MySQL 操作產生的文本錯誤信息
mysql_fetch_array() — 從結果集中取得一行作爲關聯數組,或數字數組,或二者兼有
mysql_fetch_assoc() — 從結果集中取得一行作爲關聯數組
mysql_free_result() — 釋放結果內存
mysql_info() — 取得最近一條查詢的信息 
mysql_insert_id() — 取得上一步 INSERT 操作產生的 ID 
如果AUTO_INCREMENT 的列的類型是 BIGINT,則 mysql_insert_id() 返回的值將不正確。可以在 SQL 查詢中用 MySQL 內部的 SQL 函數 LAST_INSERT_ID() 來替代
mysql_query() — 發送一條 MySQL 查詢
mysql_result() — 取得結果數據
mysql_set_charset('utf8') — 設置客戶端的字符集




mysql_close()                   關閉數據庫。


判斷操作是否成功:

1,插入操作
mysql_insert_id()>0

2,刪除操作
mysql_affected_rows()>0

3,修改操作
mysql_affected_rows()>0

4,查詢
mysql_num_rows($result)>0


數據庫函數:
取得當前時間可用 now() 函數
格式化時間字符串用DATE_FORMA T( )。 














+++++++++++++++++++++++++++++select+++++++++++++++++++++++++
header("content-type:text/html;charset=utf-8");
一:鏈接數據庫
$link = @mysql_connect('localhost','root','') or die("鏈接數據庫失敗");【這裏寫 or die()就不寫errno函數】
if(mysql_errno()){    //判斷是否鏈接成功  mysql_error(); 返回數據操作的錯誤信息
  echo '鏈接數據庫失敗'.mysql_error();   //mysql_error(); 返回數據操作的錯誤信息
  exit();
}

二:選擇數據庫
mysql_select_db('bbs85');

三:,設置字符集//等同於mysql_query('set names utf8')
mysql_set_charset('utf8');

四:準備sql語句
$sql = "select * from bbs_user";

五:,發送SQL語句,並返回執行結果
$result = mysql_query($sql);

六:判斷執行結果
if(mysql_num_rows($result)>0){   //mysql_num_rows($result); 返回結果集中數據的條數

  七:處理結果集
  while($row = mysql_fetch_assoc($result)){
    echo '<tr>';
    echo '<td>'.$row['id'].'</td>';
    echo '<td>'.$row['username'].'</td>';
    echo '<td>'.$row['email'].'</td>';
    echo '<td>'.$row['regtime'].'</td>';
    echo '<td><a href="edit.php?id='.$row['id'].'">修改</a>|<a href="delete.php?id='.$row['id'].'">刪除</a></td>';
    echo '</tr>';
  }
}

八:釋放結果集關閉數據庫
mysql_free_result($result);   // 釋放結果集只針對select查詢
mysql_close();

++++++++++++++++++++++++++++++update++++delete++++++++++++++++++++++
header("content-type:text/html;charset=utf-8");
$id = intval($_GET['id']);
if(empty($id)){
  echo '<script type="text/javascript">alert("非法參數");window.location="01link.php";</script>';
  exit();
}
//1,鏈接數據庫
$link = @mysql_connect('localhost','root','');
//判斷是否鏈接成功
if(mysql_errno()){
  echo '鏈接數據庫失敗'.mysql_error();
  exit();
}

$sql = "update bbs_user set email='$email' where id='$id'";   更新
$sql = "delete from bbs_user where id='$id'";           刪除

$result = mysql_query($sql);

//mysql_affected_rows()或去最近一次操作,所影響的數據條數 update,delete 
if(mysql_affected_rows()>0){
  echo '<script type="text/javascript">alert("修改成功");window.location="01link.php";</script>';
}else{
  echo '<script type="text/javascript">alert("修改失敗");window.location="edit.php?id='.$id.'";</script>';
}

mysql_close();
+++++++++++++++++++++++++++註冊用戶(是否被註冊)+++++++++++++++++++++++++
1,獲取用戶的輸入 2,鏈接數據庫 3,查詢是否被註冊 4,註冊
header("content-type:text/html;charset=utf-8");
$username = trim($_POST['username']);
$email = trim($_POST['email']);

$link = mysql_connect('localhost','root','') or die("鏈接數據庫失敗");
mysql_select_db('bbs85');
mysql_set_charset('utf8');

//查詢用戶名是否被註冊
$sql = "select * from bbs_user where username='$username'"; 
$result = mysql_query($sql);

if(mysql_num_rows($result)>0){
  echo '<script type="text/javascript">alert("該用戶名已經被註冊,請重新註冊");window.location="add.php";</script>';
  exit();
}

$sql = "insert into bbs_user(username,email)values('$username','$email')";
$result = mysql_query($sql);
if(mysql_insert_id()>0){
  echo '<script type="text/javascript">alert("添加用戶成功");window.location="01link.php";</script>';
}else{
  echo '<script type="text/javascript">alert("添加用戶失敗");window.location="01link.php";</script>';
}

mysql_close();
++++++++++++++++++++++++/多個服務器數據操作方式++++++++++++++++++++++++++
$link1 = mysql_connect('localhost','root','') or die("數據庫1鏈接失敗");
$link2 = mysql_connect("192.168.120.49",'root','') or die('數據2鏈接失敗');

mysql_select_db('bbs85',$link1);
mysql_select_db('bbs85',$link2);
mysql_set_charset('utf8',$link1);
mysql_set_charset('gbk',$lik2)

$sql = "select * from bbs_user";
$result1 = mysql_query($sql,$link1);
$result2 = mysql_query($sql,$link2);

if($result1 && mysql_num_rows($result1)>0){
  $row1 = mysql_fetch_assoc($result1);
}
if($result2 && mysql_num_rows($result2)>0){
  $row2 = mysql_fetch_assoc($result2);
}

mysql_close($link1);
mysql_close($link2);

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  //$row = mysql_fetch_assoc($result); 返回關聯數組,下標是字段名
  //$row = mysql_fetch_row($result); 返回索引數組,下標是字段的索引位置
  //$row = mysql_fetch_array($result); 返回混合數組 ,下標是字段的值和索引位置
  //$row = mysql_fetch_object($result);從結果集中取得一行作爲對象

// mixed mysql_result ( resource $result , int $row [, mixed $field ] )
            資源$result,      偏移量   字段名(字段表.字段名)
//取得結果集中字段的數目
echo mysql_num_fields($result); 




發佈了86 篇原創文章 · 獲贊 18 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章