ruby on rails操作mysql數據庫

一、插入:
    1、new()方法
    a = Category.new(:name => 'Ruby', :position => 1)
    a.save
    save 還有相同方法”save!”
    有無驚歎號的差別在於validate資料驗證不正確的動作,
    無驚歎號版本會回傳布林值(true或false),有驚歎號版本則是驗證錯誤會丟出例外。

    2、create()方法
    b = Category.create(:name => 'Perl', :position => 2)
    create也有“create!”方法,作用同save
    create在執行的時候已經將資料插入數據庫,無須再調用save方法
    b.save(:validate => false)
    透過:valiate => false 可以略過驗證
    create雖然無需再調用save方法,但仍然可以調用save方法。

二、查詢
    Category.first取出第一條記錄
    Category.last 取出最後一條記錄
    Category.all取出所有
    Category.find(1)取出id=1的記錄
    Category.find(1, 3)或者Category.find([1, 3]) 取出id爲1和3的記錄

     find方法會在沒有取到符合條件的記錄時拋出錯誤
     如果你不想這樣,請用:find_by_id
     Category.find_by_name('Ruby')取出name字段等於“Ruby”的記錄
   
     可以用and進行多字段查詢Category.find_by_name_and_postion('Ruby', 1)取出name='ruby' and postion=1的記錄

     find_by_* 和 find_all_by_*它們的不同之處是前者會進行“limit 1”限制

     通用方法:
     Category.find_by_sql("SELECT * FROM categories WHERE name LIKE '%p%'")如果你想自己手寫sql就可以使用這個方法,find_by_sql沒有“find_all_by_sql”方法
    Category.where(:name => 'Ruby', :position => 1),`name` = 'Ruby' AND `position` = 1
    Category.where(["name = ? or position = ?", 'Ruby', 3]), `name` = 'Ruby' OR `position` = 3另外,where 是lazy loading,也就是直到真的需要取值的時候,纔會跟資料庫拿資料。

    如果需要立即觸發,可以接着使用.all, .first, .last,例如:Category.where(["name = ? or position = ?", 'Ruby', 3]).all
    Category.limit(5).all
    限制查詢記錄數,它只接受這一個參數,如果要使用形如:“limit x, y"請組合使用“offset”方法:Category.limit(3).offset(2), 從第二條開始顯示3條記錄

    Category.order("position")
    Category.order("position DESC")
    Category.order("position DESC, name ASC")  對內容排序
    Category.order("position").reorder("name")  改用name 排序
    Category.order("position").reorder(nil)    取消所有排序
    Category.select('id, name')   只查詢出id,name欄位的數據
    Category.readonly.first    使用readonly可以使查詢出來的結果不能再次改變其值

     以上查詢方法可以進行無順序的自由的串接:
     Category.select(..).order(..).limit(.)....
     Category.where("position > 1").find_each do |category|
            category.do_some_thing
     end
     如果資料量很大,但是又需要全部拿出來處理,可以使用find_each 批次處理:
    Category.find_each(:batch_size => 2) do |category|
            puts category.id
    end
    預設會批次查出1000條,如果需要設定可以加上:batch_size 參數。
    c = Category.all 
    c.reload  reload 重新查詢出結果給c
    c = Category.first

三、刪除

    c.destory   刪除id = c.id的資料
    Category.delete(2)   刪除id = 2的資料

四、集合
    Category.count  獲取記錄總數
    Category.average(:position)
    Category.maximum(:position)
    Category.sum(:position)

    Category.where(["position>?", 2]).count      用where縮小範圍

    alreadySendNum = (Message.find :all, :conditions=>['department_id = ? and status = ?', params[:id],'published']).size          統計數組元素個數

    alreadySendNum = (Message.find :all, :conditions=>['department_id in (?) and status = ?', myArray,'published']).size             統計數組元素個數


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章