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;
            }

        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值