数据库程序设计

作者在 2010-11-30 22:36:36 发布以下内容
  c#和数据库的结合编程,给我打击挺大的,让我摸不着头脑,不知道该干嘛了。
  首先是c#与数据库的链接,开始学的几天,写不出来。过来几天,好多了。有些概念不明白,不知道他们到底用来干嘛的,什么时候用,给怎么用,只能参考老师给的代码,做了之后还是没感觉,自己还是写不出来,书上写的太抽象了,例子又不明显,没有针对性。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace dddd
{
    
    public partial class Form1 : Form
    {
        private SqlConnection dbConnection;
        private SqlDataAdapter adapter;
        private DataSet ds;
        DataGridView dataGrid;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string conn;
            conn = "Data Source=localhost;Initial Catalog=lunwen;Integrated Security=true";
            dbConnection = new SqlConnection();
            dbConnection.ConnectionString = conn;
            label1.Text = "连接成功";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
            try
            {
                string sqlString;
                sqlString = "SELECT * FROM 产品;";
                adapter = new SqlDataAdapter(sqlString, dbConnection);
               ds = new DataSet();
                adapter.Fill(ds, "changpin");
                
                dataGridView1.DataSource = ds;
                dataGridView1.DataMember = "changpin";
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }

        private void 更新_Click(object sender, EventArgs e)
        {
            bindUpdataCommand();
            try
            {
                adapter.Update(ds, "chanpin");
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message,"更新数据库失败");
            }
        }
        private void bindUpdataCommand()
        {
            string sqlstring = "UPDATA 产品 SET 产品ID=@number,产品名称=@name,供应商ID=@gys where 供应商ID=@gys";
            SqlCommand updataCommand = new SqlCommand(sqlstring,dbConnection);
            updataCommand.Parameters.Add("@number",SqlDbType.Int,20,"产品ID");
            updataCommand.Parameters.Add("@name",SqlDbType.Char,20,"产品名称");
            updataCommand.Parameters.Add("@gys",SqlDbType.Int,10,"供应商ID");
            SqlParameter parameters = new SqlParameter("@gys",SqlDbType.Int);
            parameters.SourceColumn = "供应商ID";
            parameters.SourceVersion = DataRowVersion.Original;
            updataCommand.Parameters.Add(parameters);
            adapter.UpdateCommand = updataCommand;
        }
    }
}
我的代码写出来,可以与数据库连接了,也显示出来了,就是没法更新数据库,我不知道bindUpdataCommand()是什么,还需要花时间去研究。
不过,能实现和数据库的连接和显示数据库我还是有成果的,对于刚接触这一块的我来说,我会把它搞定的。
c#学习之路 | 阅读 517 次
文章评论,共0条
游客请输入验证码
浏览928次
文章归档
最新评论