1. 程式人生 > >c# sql資料庫基本操作

c# sql資料庫基本操作

SqlConnection conn = DBConnection.MyConnection();//得到資料庫連線物件


        /// <summary>
        /// 操作資料庫,執行各種SQL語句
        /// </summary>
        /// <param name="strSql">SQL語句</param>
        /// <returns>方法返回受影響的行數</returns>
        public int OperateData(string strSql)
        {
            conn.Open();//開啟資料庫連線
            SqlCommand cmd = new SqlCommand(strSql, conn);//建立命令物件
            int i = (int)cmd.ExecuteNonQuery();//執行SQL命令
            conn.Close();//關閉資料庫連線
            return i;//返回數值
       

        /// <summary>
        /// 方法用於繫結DataGridView控制元件
        /// </summary>
        /// <param name="dgv">DataGridView控制元件</param>
        /// <param name="sql">SQL語句</param>
        public void BindDataGridView(DataGridView dgv, string sql)
        {
            SqlDataAdapter sda = new SqlDataAdapter(sql, conn);//建立資料介面卡物件
            DataSet ds = new DataSet();//建立資料集物件
            sda.Fill(ds);//填充資料集
            dgv.DataSource = ds.Tables[0];//繫結到資料表
            ds.Dispose();//釋放資源
        }

、、、、、、、、、、、、、、、、、、、、、水晶報表

 string strg = Application.StartupPath.ToString();//得到應用程式路徑
            strg = strg.Substring(0, strg.LastIndexOf("\\"));//擷取路徑資訊
            strg = strg.Substring(0, strg.LastIndexOf("\\"));//擷取路徑資訊
            strg += @"\CrystalReport";//新增路徑資訊
            strg += @"\UserPrize.rpt";//新增檔名稱
            crystalReportViewer1.ReportSource = strg;//繫結到控制元件


        /// <summary>
        /// 查詢指定資料表的人數
        /// </summary>
        /// <param name="strsql">SQL語句</param>
        /// <returns>方法返回指定記錄的數量</returns>
        public int HumanNum(string strsql)
        {
            conn.Open();//開啟資料庫連線
            SqlCommand cmd = new SqlCommand(strsql, conn);//建立命令物件
            int i = (int)cmd.ExecuteScalar();//執行SQL命令
            conn.Close();//關閉資料庫連線
            return i;//返回數值
        }


        /// <summary>
        /// 顯示選擇的圖片
        /// </summary>
        /// <param name="openF">影象檔案的路徑</param>
        /// <param name="MyImage">PictureBox控制元件</param>
        public void Read_Image(OpenFileDialog openF, PictureBox MyImage)
        {
            openF.Filter = "*.jpg|*.jpg|*.bmp|*.bmp";//篩選開啟檔案的格式
            if (openF.ShowDialog() == DialogResult.OK)//如果打開了圖片檔案
            {
                try
                {
                    MyImage.Image = System.Drawing.Image.//設定PictureBox控制元件的Image屬性
                        FromFile(openF.FileName);
                }
                catch
                {
                    MessageBox.Show("您選擇的圖片不能被讀取或檔案型別不對!",//彈出訊息對話方塊
                        "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }


        /// <summary>
        /// 將圖片以二進位制存入資料庫中
        /// </summary>
        /// <param name="MID">員工編號</param>
        /// <param name="openF">開啟檔案對話方塊物件</param>
        public void SaveImage(string MID, OpenFileDialog openF)
        {
            string P_str = openF.FileName;//得到圖片的所在路徑
            FileStream fs = new FileStream(//建立檔案流物件
                P_str, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);//建立二進位制讀取器
            byte[] imgBytesIn = br.ReadBytes((int)fs.Length);//將流讀入到位元組陣列中
            conn.Open();//開啟資料庫連線
            StringBuilder strSql = new StringBuilder();//建立字串構造器
            strSql.Append(//附加字串
                "update tb_employee Set
[email protected]
where employeeID=" + MID);
            SqlCommand cmd = new SqlCommand(strSql.ToString(), conn);//建立命令物件
            cmd.Parameters.Add("@Photo", SqlDbType.Binary).Value = imgBytesIn;//新增引數
            cmd.ExecuteNonQuery();//執行SQL命令
            conn.Close();//關閉資料庫連線
        }


        /// <summary>
        /// 將圖片從資料庫中取出
        /// </summary>
        /// <param name="ygname">員工編號</param>
        /// <param name="pb">PictureBox物件</param>
        public void Get_Image(string ygname, PictureBox pb)
        {
            byte[] imagebytes = null;//宣告位元組陣列變數
            conn.Open();//開啟資料庫連線
            SqlCommand com = new SqlCommand(//建立命令物件
                "select * from tb_employee where employeeID='" + ygname + "'", conn);
            SqlDataReader dr = com.ExecuteReader();//執行SQl命令
            while (dr.Read())//讀取資料庫中的資料
            {
                imagebytes = (byte[])dr.GetValue(11);//得到圖象的位元組資料
            } 
            dr.Close();//關閉資料讀取器 
            conn.Close();//關閉資料庫連線
            MemoryStream ms = new MemoryStream(imagebytes);//建立記憶體流物件
            Bitmap bmpt = new Bitmap(ms);//得到BMP物件
           
            pb.Image = bmpt;//顯示影象資訊
        }


        /// <summary>
        /// 使用此方法可以得到資料集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns>方法返回資料集</returns>
        public DataSet GetTable(string sql)
        {
            SqlDataAdapter sda = new SqlDataAdapter(sql, conn);//建立資料介面卡物件
            DataSet ds = new DataSet();//建立資料集
            sda.Fill(ds);//填充資料集
            ds.Dispose();//釋放資源
            return ds;//返回資料集
        }


        /// <summary>
        /// //繫結下拉列表
        /// </summary>
        /// <param name="strTable">資料庫表名</param>
        /// <param name="cb">ComboBox物件</param>
        /// <param name="i">指定資料列索引</param>
        public void BindDropdownlist(string strTable, ComboBox cb, int i)
        {
            conn.Open();//開啟資料庫連線
            SqlCommand cmd = new SqlCommand(//建立命令物件
                "select * from " + strTable, conn);
            SqlDataReader sdr = cmd.ExecuteReader();//得到資料讀取器
            while (sdr.Read())
            {
                cb.Items.Add(sdr[i].ToString());//新增資訊
            }
            conn.Close();//關閉資料庫連線
        }

、、、、、、、、、、、、、、、、、、、、、、、、、

、、、、、、、、、、、、、、、、、、備份sql資料庫、、、、、、、、、、、、

strg = Application.StartupPath.ToString();//得到應用程式路徑
                strg = strg.Substring(0, strg.LastIndexOf("\\"));//擷取路徑
                strg = strg.Substring(0, strg.LastIndexOf("\\"));//擷取路徑
                strg += @"\Backup";//新增路徑資訊
                string sqltxt =//設定SQL字串
                    @"BACKUP DATABASE db_PMS TO Disk='" + strg + "\\PMS.bak" + "'";
                if (File.Exists(strg + "\\PMS.bak"))//判斷檔案是否存在
                {
                    File.Delete(strg + "\\PMS.bak");//刪除檔案
                    SqlConnection conn = DBConnection.MyConnection();//建立資料庫連線物件
                    conn.Open();//連線資料庫
                    SqlCommand cmd = new SqlCommand(sqltxt, conn);//建立資料庫命令物件
                    cmd.ExecuteNonQuery();//執行操作
                    conn.Dispose();//釋放資料庫連線資源
                    if (MessageBox.Show("備份成功", "提示", MessageBoxButtons.OK,//彈出訊息對話方塊
                        MessageBoxIcon.Exclamation) == DialogResult.OK)
                    {
                        this.Close();//關閉窗體
                    }
                }
                else
                {
                    SqlConnection conn = DBConnection.MyConnection();//建立資料庫連線物件
                    conn.Open();//連線資料庫
                    SqlCommand cmd = new SqlCommand(sqltxt, conn);//建立資料庫命令物件
                    cmd.ExecuteNonQuery();//執行操作
                    conn.Dispose();//釋放資料庫連線資源
                    if (MessageBox.Show("備份成功", "提示", MessageBoxButtons.OK,//彈出訊息對話方塊
                        MessageBoxIcon.Exclamation) == DialogResult.OK)
                    {
                        this.Close();//關閉窗體
                    }
                }
            }
            catch (Exception ex)//捕獲異常
            {
                MessageBox.Show(ex.Message.ToString(), "提示",//彈出訊息對話方塊
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

       、、、、、、、、、、、、、、、、水晶報表的呼叫,當窗體載入時

          string strg = Application.StartupPath.ToString();//得到應用程式路徑
            strg = strg.Substring(0, strg.LastIndexOf("\\"));//擷取路徑資訊
            strg = strg.Substring(0, strg.LastIndexOf("\\"));//擷取路徑資訊
            strg += @"\CrystalReport";//新增路徑資訊
            strg += @"\UserPrize.rpt";//新增檔名稱
            crystalReportViewer1.ReportSource = strg;//繫結到控制元件

        

相關推薦

c# sql資料庫基本操作

SqlConnection conn = DBConnection.MyConnection();//得到資料庫連線物件         /// <summary>         /// 操作資料庫,執行各種SQL語句         /// </sum

SQL資料庫基本操作對應Shell指令碼檔案處理

一、前言 日常工作中,一些資料統計的源資料是檔案,因為檔案資料統計不像資料庫操作那樣方便,如果匯入資料庫再進行操作,可能比較麻煩;因此,這裡將SQL資料庫基本操作與Shell對檔案資料操作進行對應,方便用Shell的語法進行檔案處理。這裡分別用Oracle SQL與shel

例題SQL語句詳解-資料庫基本操作1

1.1 連線伺服器 通過命令列面板連線 host:主機 -h username:使用者名稱 -u password:密碼 -p port:埠 -P 多學一招:如果MySQL伺服器在本地,IP

例題SQL語句詳解-資料庫基本操作2

1.4 表的操作 1.4.1 顯示所有表 語法: show tables 1.4.2 建立表 語法: create table [if not exists] 表名( 欄位名 資料型別 [null|not null] [auto_in

例題SQL語句詳解-資料庫基本操作4

1.6 SQL分類 DDL(data definition language)資料庫定義語言create、alter、drop、shop DML(data manipulation language)資料操縱語言select、update、ins

例題SQL語句詳解-資料庫基本操作6-資料型別拓展

1.3 資料型別——列舉(enum) 1、從集合中選擇一個數據(單選) mysql> create table t8( -> name varchar(20), -> sex enum('男','女','保密')

例題SQL語句詳解-資料庫基本操作7-資料型別拓展

| 1.6 資料型別——boolean MySQL不支援boolean型別,true和false在資料庫中對應1和0。 mysql> create table t15( -> field boolean -> ); Query

例題SQL語句詳解-資料庫基本操作9-完整性介紹

| 1.15 資料完整性介紹 1.15.1 保證實體完整性 1、 主鍵約束 2、 唯一約束 3、 自動增長列 1.15.2 保證域完整性 1、 資料型別約束 2、 非空約束 3、 預設值約束 1.15.3

例題SQL語句詳解-資料庫基本操作10-查詢語句

|版權宣告:本文為博主原創文章,未經博主允許不得轉載。轉載請附上原連結,部落格地址:https://blog.csdn.net/sgsgy5 1.6 查詢語句 語法:select [選項] 列名 [from 表名] [where 條件] [group by

例題SQL語句詳解-資料庫基本操作11-排序分組聯合

| 1.6.11 order by排序 asc:升序【預設】 desc:降序 mysql> select * from stu order by ch desc; # 語文成績降序排列 mysql> select * from stu orde

Sql Server基本操作資料庫 表 檢視

一.對資料庫的操作 1.查詢系統所有資料庫 select * from sysdatabases 2.刪除某個資料庫 drop database dbtest 3.建立某個資料庫 create database dbtest ON PRIMARY ( NAME = ‘dbtest’, FIL

Oracle操作筆記——資料庫基本操作SQL命令

文章目錄 單表查詢 查詢結果拼接用|| 條件判斷用CASE WHEN 限制返回的行數用rownum 隨機返回用dbms_random.value() 模糊查詢用% _ \ 對結果排序用ORD

如何從零開始快速學習sql sever 資料庫基本操作-建庫/表-刪庫/表

環境配置 1.安裝sql sever 資料庫到本地,我用的是sql sever2014版,至於如何安裝請百度吧,學會用搜索工具很重要的,我就不在此囉嗦了。 2.連結上資料庫。 看到紅色框裡面就是各個資料庫名,有些是sql sever 自帶的,有些是我自己建立的,本文主要講述

SQL server 練習1(SQL server 資料庫基本操作

  本篇部落格用來記錄,編者做sql server練習的題目及解答,以及遇到的一些問題和總結。 題目 1、資料庫建立 名稱:stuManage 主資料檔案: 邏輯檔名:stuManage_M_data 物理檔名:stuManage__data

資料庫入門之--Navicat Premium快捷鍵&SQL Server基本操作語句

前提:這裡不拔高到開發高度,只做測試用的基本增刪改查 資料庫安裝: Microsoft SQL Server 2008 、MySQL,如下圖:(SQL Server和MySQLl的區別) 然後用Navicat Premium管理資料庫,這些安裝包都百度的到,就不上傳

T-SQL語句操作資料庫——基本操作

一、建立刪除資料資料庫 1、T-SQL語句建立資料庫語法如下: CREATE DATABASE 資料庫名 ON [PRINARY] ( <檔案引數>[,...n] [<檔案組引數>] ) [LOG ON] ( {<日誌檔案引數>}[,...n] ) 檔案

SQL Server 基本操作之三種增加法

一次 增刪改查 sql 數據的操作 插入 table 增長 類型 val 前言:     數據庫操作避免不了對數據的操作,操作方法大同小異,萬變不離其宗,今就寫一下各種花式操作的根本增刪改查四種操作,今天我們就來說一下增加操作的三種方法 正文:   增加操作是對數據庫進

08.SQL Server 基本操作【分離(脫機)、附加(聯機)】

原因 -1 文件的操作 刪除 方法 附加 文件 技術分享 屬性 1、創建、刪除(對準數據庫右鍵)2、分離(脫機)、附加(聯機) 關於附加數據庫失敗的處理:原因:對文件的操作權限不夠處理方法:對準mdf文件和ldf文件 右鍵 屬性 安全性將 用戶 Users

C 棧的基本操作

直接上程式碼 // // main.c // 棧的操作 // // Created by 赫凱 on 2018/10/25. // Copyright © 2018 赫凱. All rights reserved. // #include <stdio.h> #

mysql資料庫基本操作注意點

對於一個初學資料庫的人來說,最主要的還是要掌握DQL資料庫查詢語言和DML資料操作語言。 這裡主要對DQL進行簡單的總結,實質就是學習的筆記。 資料查詢語言基本的語句結構為select * from table_name; 1. 條件語句where關建字,支援多種運算子 比較運