Sql 常用的語句實例與代碼


在學習SQL的時候,本來預計花三天的時候掌握MS SQL這些基礎,現在爭取提前一天看完。總結沉底下來,其實也沒有多少東西:

 

1、程序初始化前,先連接數據庫

 

       MFC程序中添加記錄的代碼:

[cpp]   view plain copy print ?
  1. /************************************************************************/  
  2. /* 函數作用: 對話框默認初始化函數,連接SQL數據庫、添加列表頭 
  3. /* 函數參數: 無 
  4. /* 返 回 值: 成功返回TRUE,否則返回FALSE 
  5. /* 說    明: By Koma 2009-08-20 20:18 Edit 
  6. /************************************************************************/  
  7. BOOL CQDlg::OnInitDialog()  
  8. {  
  9.     CDialog::OnInitDialog();  
  10.   
  11.     // Add "About..." menu item to system menu.  
  12.   
  13.     // IDM_ABOUTBOX must be in the system command range.  
  14.     ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);  
  15.     ASSERT(IDM_ABOUTBOX < 0xF000);  
  16.   
  17.     CMenu* pSysMenu = GetSystemMenu(FALSE);  
  18.     if (pSysMenu != NULL)  
  19.     {  
  20.         CString strAboutMenu;  
  21.         strAboutMenu.LoadString(IDS_ABOUTBOX);  
  22.         if (!strAboutMenu.IsEmpty())  
  23.         {  
  24.             pSysMenu->AppendMenu(MF_SEPARATOR);  
  25.             pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);  
  26.         }  
  27.     }  
  28.   
  29.     // Set the icon for this dialog.  The framework does this automatically  
  30.     //  when the application's main window is not a dialog  
  31.     SetIcon(m_hIcon, TRUE);         // Set big icon  
  32.     SetIcon(m_hIcon, FALSE);        // Set small icon  
  33.       
  34.     // TODO: Add extra initialization here  
  35.     //初始化COM接口  
  36.     if (!AfxOleInit())  
  37.     {  
  38.         AfxMessageBox("初始化com接口失敗");  
  39.     }  
  40.     HRESULT hr;   
  41.     try   
  42.     {   
  43.         // 創建Connection對象  
  44.         hr = m_pConnection.CreateInstance("ADODB.Connection");   
  45.         if(SUCCEEDED(hr))   
  46.         {  
  47.             // 連接數據庫成功  
  48.             hr = m_pConnection->Open("Provider=SQLOLEDB;Server=koma.5166.info,1433;DataBase=student;UID=sa;PWD=","","",adModeUnknown);  
  49.         }   
  50.     }   
  51.     catch(_com_error e)   
  52.     {  
  53.         // 捕捉異常  
  54.         CString errormessage;   
  55.         errormessage.Format("連接數據庫失敗!/r/n錯誤信息:%s",e.ErrorMessage());   
  56.         AfxMessageBox(errormessage);///顯示錯誤信息   
  57.     }   
  58.   
  59.     // 上下列表控件初始化XP風格  
  60.     LONG lStyle = m_LineList.SendMessage(LVM_GETEXTENDEDLISTVIEWSTYLE);  
  61.     lStyle |=  LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES;  
  62.     m_LineList.SendMessage(LVM_SETEXTENDEDLISTVIEWSTYLE, 0,(LPARAM)lStyle);  
  63.   
  64.     //  添加ListBox列表頭  
  65.     m_LineList.InsertColumn(0,"姓名", NULL,80, -1);  
  66.     m_LineList.InsertColumn(1,"班級", NULL,80,-1);  
  67.     m_LineList.InsertColumn(2,"語文", NULL,80,-1);  
  68.     m_LineList.InsertColumn(3,"數學", NULL,80, -1);  
  69.     m_LineList.InsertColumn(4,"英語", NULL,80, -1);  
  70.   
  71.     return TRUE;  // return TRUE  unless you set the focus to a control  
  72. }  

 

 

2、選擇表名

 

      例句:use student  這條語句一般在SQL查詢分析器中需要使用到,而在程序中我覺得並不需要。

 

3、讀取記錄

 

      SQL查詢分析器中例句:

 

      use student

 

      select * from db_info

 

      MFC程序中添加記錄的代碼:

[cpp]   view plain copy print ?
  1. /************************************************************************/  
  2. /* 函數作用: 讀取SQL數據庫記錄,將內容寫入ListBox 
  3. /* 函數參數: 無 
  4. /* 返 回 值: 無 
  5. /* 說    明: By Koma 2009-08-20 21:35 Edit 
  6. /************************************************************************/  
  7. void CQDlg::OnBtnRead()   
  8. {  
  9.     // TODO: Add your control notification handler code here  
  10.     //  清空列表框  
  11.     m_LineList.DeleteAllItems();  
  12.       
  13.     int nItem;  
  14.     _variant_t vName,vBanJi,vYuWen,vShuXue,vYinWen;  
  15.     try  
  16.     {  
  17.         // 連接數據庫,打開MainInfo表  
  18.         m_pRecordset.CreateInstance("ADODB.Recordset");   
  19.         m_pRecordset->Open("select * from db_info",_variant_t((IDispatch*)  
  20.             m_pConnection,TRUE),adOpenStatic,adLockOptimistic,adCmdText);  
  21.           
  22.         // 判斷記錄集指針標志,是否讀取完畢  
  23.         while(!m_pRecordset->adoEOF)  
  24.         {  
  25.             // 獲取記錄集  
  26.             vName   = m_pRecordset->GetCollect("姓名");  
  27.             vBanJi  = m_pRecordset->GetCollect("班級");  
  28.             vYuWen  = m_pRecordset->GetCollect("語文");  
  29.             vShuXue = m_pRecordset->GetCollect("數學");  
  30.             vYinWen = m_pRecordset->GetCollect("英語");  
  31.   
  32.             // 更新上面的ListBox  
  33.             nItem = m_LineList.InsertItem(0xffff,(_bstr_t)vName);  
  34.             m_LineList.SetItem(nItem,1,1,(_bstr_t)vBanJi,NULL,0,0,0);  
  35.             m_LineList.SetItem(nItem,2,1,(_bstr_t)vYuWen,NULL,0,0,0);  
  36.             m_LineList.SetItem(nItem,3,1,(_bstr_t)vShuXue,NULL,0,0,0);  
  37.             m_LineList.SetItem(nItem,4,1,(_bstr_t)vYinWen,NULL,0,0,0);  
  38.               
  39.             // 移動記錄集指針到下一條  
  40.             m_pRecordset->MoveNext();  
  41.             Sleep(5);  
  42.         }  
  43.     }  
  44.     catch (_com_error e)  
  45.     {  
  46.         // 讀取出數據庫記錄出錯  
  47.         CString strTemp;  
  48.         strTemp.Format("讀取數據庫時出錯,錯誤代碼:『%s』",GetLastError());  
  49.         AfxMessageBox(strTemp);  
  50.     }  
  51. }  

 

 

4、添加記錄

 

      SQL查詢分析器中例句:

 

      insert into db_info ([姓名],[班級],[語文],[數學],[英語]) values ('鄧麗君','二年三班','98','94','100') 

 

      MFC程序中添加記錄的代碼:

[cpp]   view plain copy print ?
  1. /************************************************************************/  
  2. /* 函數作用: 讀取SQL數據庫,添加記錄集 
  3. /* 函數參數: 無 
  4. /* 返 回 值: 無 
  5. /* 說    明: By Koma 2009-08-20 22:45 Edit 
  6. /************************************************************************/  
  7. void CQDlg::OnBtnAdd()   
  8. {  
  9.     // TODO: Add your control notification handler code here  
  10.     try  
  11.     {  
  12.         UpdateData(TRUE);  
  13.         CString sql;  
  14.         m_pRecordset.CreateInstance("ADODB.Recordset");  
  15.         m_pRecordset->Open("select * from db_info",_variant_t((IDispatch*)  
  16.             m_pConnection,TRUE),adOpenStatic,adLockBatchOptimistic,adCmdText);  
  17.         sql.Format("insert into db_info ([姓名],[班級],[語文],[數學],[英語]) values ('%s','%s','%d','%d','%d')",  
  18.                     m_Name,m_Class,m_Yuwen,m_Shuxue,m_English);  
  19.   
  20.         // 執行SQL語句  
  21.         m_pConnection->Execute((_bstr_t)sql,NULL,adExecuteNoRecords);  
  22.         MessageBox("添加成功!","提示");  
  23.     }  
  24.     catch(_com_error e)  
  25.     {  
  26.         // 添加出錯  
  27.         CString errormessage;    
  28.         errormessage.Format("添加失敗,請檢查姓名『%s』是否已經存在!/n錯誤信息:『%s』",m_Name,e.ErrorMessage());  
  29.         AfxMessageBox(errormessage);  
  30.     }  
  31. }  

 

 

5、修改記錄

 

      SQL查詢分析器中例句:

 

      update db_info set [姓名]='黃家駒',[班級]='三年三班',[語文]='97',[數學]='96',[英語]='98' where [姓名]='黃家駒'

 

      MFC程序中添加記錄的代碼:

[cpp]   view plain copy print ?
  1. /************************************************************************/  
  2. /* 函數作用: 讀取SQL數據庫,修改記錄集 
  3. /* 函數參數: 無 
  4. /* 返 回 值: 無 
  5. /* 說    明: By Koma 2009-08-20 22:58 Edit 
  6. /************************************************************************/  
  7. void CQDlg::OnBtnEdit()   
  8. {  
  9.     // TODO: Add your control notification handler code here  
  10.     try  
  11.     {  
  12.         // 修改數據,以姓名為鍵  
  13.         UpdateData(TRUE);  
  14.         CString sql;  
  15.         m_pRecordset.CreateInstance("ADODB.Recordset");  
  16.         m_pRecordset->Open("select * from db_info",_variant_t((IDispatch*)  
  17.             m_pConnection,TRUE),adOpenStatic,adLockBatchOptimistic,adCmdText);  
  18.         sql.Format("update db_info set [姓名]='%s',[班級]='%s',[語文]='%d',[數學]='%d',[英語]='%d' where [姓名]='%s'",  
  19.                     m_Name,m_Class,m_Yuwen,m_Shuxue,m_English,m_OldName);  
  20.   
  21.         // 執行SQL語句  
  22.         m_pConnection->Execute((_bstr_t)sql,NULL,adExecuteNoRecords);  
  23.           
  24.         // 刷新重新讀取數據庫  
  25.         OnBtnRead();  
  26.         MessageBox("修改成功!","提示");  
  27.     }  
  28.     catch(_com_error e)  
  29.     {  
  30.         // 修改失敗  
  31.         CString errormessage;    
  32.         errormessage.Format("修改失敗,錯誤信息:『%s』",e.ErrorMessage());  
  33.         AfxMessageBox(errormessage);  
  34.     }  
  35. }  

 

 

6、刪除記錄

 

      SQL查詢分析器中例句:

 

      delete from db_info where [姓名]='黃家駒'

 

 

      MFC程序中添加記錄的代碼:

[cpp]   view plain copy print ?
  1. /************************************************************************/  
  2. /* 函數作用: 讀取SQL數據庫,刪除記錄集 
  3. /* 函數參數: 無 
  4. /* 返 回 值: 無 
  5. /* 說    明: By Koma 2009-08-20 21:46 Edit 
  6. /************************************************************************/  
  7. void CQDlg::OnBtnDel()   
  8. {  
  9.     // TODO: Add your control notification handler code here  
  10.     try  
  11.     {  
  12.         UpdateData(TRUE);  
  13.         CString sql;  
  14.         m_pRecordset.CreateInstance("ADODB.Recordset");  
  15.         m_pRecordset->Open("select * from db_info",_variant_t((IDispatch*)  
  16.             m_pConnection,TRUE),adOpenStatic,adLockBatchOptimistic,adCmdText);  
  17.           
  18.         UpdateData(TRUE);  
  19.         sql.Format("delete from db_info where [姓名]='%s'",m_Name);  
  20.   
  21.         // 執行SQL語句  
  22.         m_pConnection->Execute((_bstr_t)sql,NULL,adExecuteNoRecords);  
  23.           
  24.         OnBtnRead();  
  25.         MessageBox("刪除成功!","提示");  
  26.     }  
  27.     catch(_com_error e)  
  28.     {  
  29.         CString errormessage;    
  30.         errormessage.Format("刪除失敗,錯誤信息:『%s』",e.ErrorMessage());  
  31.         AfxMessageBox(errormessage);  
  32.     }  
  33. }  

 

 

 

 

7、條件判斷

 

 

     SQL腳本中,常用的關鍵詞有:

 

 

     where、or、and、like、order by

 

 

 

      SQL查詢分析器中例句:

 

 

      A、完全符合條件:select * from db_info where [姓名]='黃家強'

 

      B、比較符合條件:select * from db_info where [語文]>='80'

      C、按語文來排序:select * from db_info where [語文]>='80' order by [語文]

 

      D、符合關鍵字的:select * from db_info where [姓名] like '%黃%'

 

      E、組合條件查詢:select * from db_info where [姓名] like '%黃%' and [語文]>=90

 

      F、組合條件查詢:select * from db_info where [姓名] like '%黃%' or [語文]>=90

 

 

 

      MFC程序中添加記錄的代碼,上面的代碼中除了帶有%關鍵字比較麻煩,其他的應該沒問題,這里舉例以字段包含某關鍵字:

[cpp]   view plain copy print ?
  1. /************************************************************************/  
  2. /* 函數作用: 查詢姓名字段包含某關鍵字的記錄集 
  3. /* 函數參數: 默認 
  4. /* 返 回 值: 無 
  5. /* 說    明: By Koma 2009-08-20 23:10 Edit 
  6. /************************************************************************/  
  7. void CQDlg::OnBtnFind()   
  8. {  
  9.     // TODO: Add your control notification handler code here  
  10.     try  
  11.     {  
  12.         //  清空列表框  
  13.         UpdateData(TRUE);  
  14.         m_LineList.DeleteAllItems();  
  15.   
  16.         CString sql;  
  17.         int     nItem;  
  18.   
  19.         _variant_t vName,vBanJi,vYuWen,vShuXue,vYinWen;  
  20.         sql.Format("select * from db_info where [姓名] like /'%%%s%%/'",m_FindName);  
  21.   
  22.         m_pRecordset.CreateInstance("ADODB.Recordset");  
  23.         m_pRecordset->Open((_variant_t)sql,_variant_t((IDispatch*)  
  24.                 m_pConnection,TRUE),adOpenStatic,adLockOptimistic,adCmdText);  
  25.           
  26.         // 判斷記錄集指針標志,是否讀取完畢  
  27.         while(!m_pRecordset->adoEOF)  
  28.         {  
  29.             // 獲取記錄集  
  30.             vName   = m_pRecordset->GetCollect("姓名");  
  31.             vBanJi  = m_pRecordset->GetCollect("班級");  
  32.             vYuWen  = m_pRecordset->GetCollect("語文");  
  33.             vShuXue = m_pRecordset->GetCollect("數學");  
  34.             vYinWen = m_pRecordset->GetCollect("英語");  
  35.               
  36.             // 更新上面的ListBox  
  37.             nItem = m_LineList.InsertItem(0xffff,(_bstr_t)vName);  
  38.             m_LineList.SetItem(nItem,1,1,(_bstr_t)vBanJi,NULL,0,0,0);  
  39.             m_LineList.SetItem(nItem,2,1,(_bstr_t)vYuWen,NULL,0,0,0);  
  40.             m_LineList.SetItem(nItem,3,1,(_bstr_t)vShuXue,NULL,0,0,0);  
  41.             m_LineList.SetItem(nItem,4,1,(_bstr_t)vYinWen,NULL,0,0,0);  
  42.               
  43.             // 移動記錄集指針到下一條  
  44.             m_pRecordset->MoveNext();  
  45.             Sleep(5);  
  46.         }  
  47.         CString strTotal;  
  48.         int nTotals=m_pRecordset->GetRecordCount();  
  49.         strTotal.Format("查詢完成,總共有%d條記錄!",nTotals);  
  50.           
  51.         SetDlgItemText(IDC_STATIC_RESULT,strTotal);  
  52.     }  
  53.     catch (_com_error e)  
  54.     {  
  55.         // 讀取出數據庫記錄出錯  
  56.         CString strTemp;  
  57.         strTemp.Format("讀取數據庫時出錯,錯誤代碼:『%s』",GetLastError());  
  58.         AfxMessageBox(strTemp);  
  59.     }  
  60. }  

 

 

8、總結

 

      個人覺得,在程序設計中上面的實例與代碼應付一般的數據庫操作都沒什么問題,如果具體還需要更高級的操作的話,直接去查查聯機手機吧,“中文”稍微好點的,應該沒什么問題!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM