c# 訪問數據庫方法( 例)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient; 

namespace DatabaseDemo
{
    public partial class Form1 : Form
    {
        SqlDataAdapter sqlDataAdapter1;
        //存取數據庫的主要類
        SqlCommand sqlCommand1;
        //SQL語句處理的類
        SqlConnection sqlConnection1;
        // 表示是否處於插入新記錄的狀態
        private bool bNewRecord = false;

        // 獲取所有客戶的ID
        private void GetCustomID()
  {
   SqlDataReader sdr ;
   sqlConnection1.Open(); // 打開連接
            sdr=  sqlCommand1.ExecuteReader(CommandBehavior.CloseConnection);
   cbxID.Items.Clear();
   while( sdr.Read() ){
    // 把客戶ID插入到組合框控件中
    cbxID.Items.Add( sdr.GetValue(0) );
   }
   sdr.Close();   // 關閉SqlDataReader對象和數據庫連接
   cbxID.SelectedIndex = 0;
  }

       
        public Form1()
        {
            InitializeComponent();
        }

     private void Form1_Load(object sender, EventArgs e)
       {
       //SQL Server 登錄機制
           String sConnString = "server=.;uid=sa;pwd=;database=Northwind";

       // Windows 安全登錄機制
       //  String sConnString  = "Data Source=Highill;Initial Catalog=Northwind;Integrated Security=True";

        //SQL語句
           String sSQL = "SELECT * FROM Customers";

        //創建一個數據庫連接對象
        sqlConnection1 = new System.Data.SqlClient.SqlConnection(sConnString );
 
        sqlCommand1 = new System.Data.SqlClient.SqlCommand();
        sqlCommand1.Connection = sqlConnection1;

         sqlCommand1.CommandText = "SELECT CustomerID FROM Customers ORDER BY CustomerID"; 

       //創建一個SqlDataAdapter對象
        sqlDataAdapter1=new SqlDataAdapter(sSQL,sqlConnection1);

       // 創建一個DataSet對象
       DataSet dataSet1=new  DataSet();
        sqlDataAdapter1.Fill(dataSet1, "Customers");
        dataGridView1.DataSource = dataSet1.Tables["Customers"];
        GetCustomID();
        }

        private void cbxID_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 創建SQL命令對象
            SqlCommand sqlcmd = new SqlCommand(
                "SELECT * FROM Customers WHERE CustomerID = @ID",
                sqlConnection1);

            // 設置參數
            sqlcmd.Parameters.AddWithValue("@ID", cbxID.Text);
            SqlDataReader sdr;
            sqlConnection1.Open();
            sdr = sqlcmd.ExecuteReader();
            if (sdr.Read())
            {
                // 使用不同的方式讀取特定字段的值
                txtCompanyName.Text = sdr.GetString(1);
                txtContactName.Text = sdr["ContactName"].ToString();
                txtContactTitle.Text = sdr[3].ToString();
                txtAddress.Text = sdr.GetValue(4).ToString();
                txtCity.Text = sdr["City"].ToString();
                txtRegion.Text = sdr.GetValue(6).ToString();
                txtPostalCode.Text = sdr[7].ToString();
                txtCountry.Text = sdr[8].ToString();
                txtPhone.Text = sdr[9].ToString();
                txtFax.Text = sdr[10].ToString();
            }
            sdr.Close();
            sqlConnection1.Close();

        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (cbxID.SelectedIndex > 0)
                cbxID.SelectedIndex -= 1;

        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (cbxID.SelectedIndex < cbxID.Items.Count - 1)
                cbxID.SelectedIndex += 1;

        }

        private void btnOrder_Click(object sender, EventArgs e)
        {
            FormOrders orders = new FormOrders();
            orders.CustomerID = cbxID.Text;
            orders.ShowDialog();

        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            txtCompanyName.Text = "";
            txtContactName.Text = "";
            txtContactTitle.Text = "";
            txtAddress.Text = "";
            txtCity.Text = "";
            txtRegion.Text = "";
            txtPostalCode.Text = "";
            txtCountry.Text = "";
            txtPhone.Text = "";
            txtFax.Text = "";
            cbxID.DropDownStyle = ComboBoxStyle.DropDown;
            cbxID.Text = "";
            bNewRecord = true;  

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            SqlCommand sqlcmd = new SqlCommand(
                "DELETE FROM Customers WHERE CustomerID=@ID",
                sqlConnection1);
            sqlcmd.Parameters.AddWithValue("@ID", cbxID.Text);
            try
            {
                sqlConnection1.Open();
                int rowAffected = sqlcmd.ExecuteNonQuery();
                if (rowAffected == 1)
                    cbxID.Items.RemoveAt(cbxID.SelectedIndex);
            }
            catch (SqlException ex)
            {
                MessageBox.Show("刪除錯誤:" + ex.Message, "出現錯誤",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                sqlConnection1.Close();
            }
            if (cbxID.SelectedIndex < cbxID.Items.Count - 1)
                cbxID.SelectedIndex += 1;

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string sqlStatement;
            // 根據是否正在添加新記錄來建立適當的查詢語句
            if (bNewRecord == true)
            {
                sqlStatement = "INSERT INTO Customers VALUES(" +
                    "'" + cbxID.Text + "'," +
                    "'" + txtCompanyName.Text + "'," +
                    "'" + txtContactName.Text + "'," +
                    "'" + txtContactTitle.Text + "'," +
                    "'" + txtAddress.Text + "'," +
                    "'" + txtCity.Text + "'," +
                    "'" + txtRegion.Text + "'," +
                    "'" + txtPostalCode.Text + "'," +
                    "'" + txtCountry.Text + "'," +
                    "'" + txtPhone.Text + "'," +
                    "'" + txtFax.Text + "')";
            }
            else
            {
                sqlStatement = "UPDATE Customers SET " +
                    "CompanyName='" + txtCompanyName.Text + "'," +
                    "ContactName='" + txtContactName.Text + "'," +
                    "ContactTitle='" + txtContactTitle.Text + "'," +
                    "Address='" + txtAddress.Text + "'," +
                    "City='" + txtCity.Text + "'," +
                    "Region='" + txtRegion.Text + "'," +
                    "PostalCode='" + txtPostalCode.Text + "'," +
                    "Country='" + txtCountry.Text + "'," +
                    "Phone='" + txtPhone.Text + "'," +
                    "Fax='" + txtFax.Text + "'" +
                    "WHERE CustomerID = '" + cbxID.Text + "'";
            }
            // 創建SQL命令
            SqlCommand sqlcmd = new SqlCommand(
                sqlStatement,
                sqlConnection1);
            try
            {
                sqlConnection1.Open();
                int rowAffected = sqlcmd.ExecuteNonQuery();
                if (rowAffected == 1)
                    cbxID.Items.Add(cbxID.Text);
            }
            catch (SqlException ex)
            {
                MessageBox.Show("更新錯誤:" + ex.Message, "出現錯誤",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                sqlConnection1.Close();
            }
            if (bNewRecord == true)
            {

                cbxID.DropDownStyle = ComboBoxStyle.DropDownList;
                bNewRecord = false;
                cbxID.SelectedIndex = cbxID.Items.Count - 1;
            }

        }
    }
}

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