我想做一个Winform程序。要有一个数据库连接。请问在vs2008(C#)中如何在公用模块中设置一个连接,在所以的窗体中都能用。查资料说用类实现,可不太会。哪位能提供一下这方面的代码,非常感谢!

解决方案 »

  1.   

    你查一下三层设计模式就明白了 :      首先 新建一个项目 空白资源解决方案
          然后为解决方案 新建项目 添加类库
          我添加的1、BLL 2、DAL 3、Model
          然后创建一个网站
          再次添加引用
          我的引用是
          网站引用MODEL,BLL
          BLL引用MODEL,DAL
          DAL引用BLL
          如果你在DAL中使用了SQLHELPER等其他类的话,可能还需要添加引用,比如System.Web等
          其次就是写代码了~
          这里写一个很简单的留言的代码
          Model-Message.cs
          using System;
          using System.Collections.Generic;
          using System.Text;
          namespace Model
          {
              public class Message
              {
                  public Message() { }
                  private string _UserName;
                  public string UserName
                  {
                      set { _UserName = value; }
                      get { return _UserName; }           
                  }
                  private string _Content;
                  public string Content
                  {
                      set { _Content = value; }
                      get { return _Content; }
                  }
              }
          }
          BLL-Message.cs
          using System;
          using System.Collections.Generic;
          using System.Text;
          namespace BLL
          {
              public class Message
              {
                  DAL.Message Add = new DAL.Message();
                  public bool adduser(Model.Message model)
                  {
                      return Add.addMessage(model);
                  }
              }
          }
          DAL-Message.cs
          using System;
          using System.Collections.Generic;
          using System.Text;      namespace DAL
          {
              public class Message
                 
              {
                  public bool addMessage(Model.Message model)
                  {
                      string sSql = "INSERT INTO [GuestBook]([Title],[Content]) 
          VALUES('" + model.UserName + "','" + model.Content + "')";
                      if (DBFun.ExecuteUpdate(sSql))
                          return true;
                      else return false;
                  }
              }
          }
      

  2.   

    上一次不够清楚 再发一个详细的:1.三层之间的关系: 
    三层是指:界面显示层(UI),业务逻辑层(Business),数据操作层(Data Access)
    文字描述:
    Clients对UI进行操作,UI调用Business进行相应的运算和处理,Business通过Data Access对Data Base进行操作。
    优点:
    l         增加了代码的重用。Data Access可在多个项目中公用;Business可在同一项目的不同地方使用(如某个软件B/S和C/S部分可以共用一系列的Business组件)。
    l         使得软件的分层更加明晰,便于开发和维护。美工人员可以很方便地设计UI设计,并在其中调用Business给出的接口,而程序开发人员则可以专注的进行代码的编写和功能的实现。
    2.Data Access的具体实现:
    DataAgent类型中变量和方法的说明:
    private string m_strConnectionString; //连接字符串
    private OleDbConnection m_objConnection; //数据库连接
    public DataAgent(string strConnection) //构造方法,传入的参数为连接字符串
    private void OpenDataBase() //打开数据库连接
    private void #region CloseDataBase() //关闭数据库连接
    public DataView GetDataView(string strSqlStat) //根据传入的连接字符串返回DataView
    具体实现代码如下:
    public class DataAgent
    {
        private string m_strConnectionString;
        private OleDbConnection m_objConnection;
        #region DataAgend
        ///<summary>
        /// Initial Function
        ///</summary>
        ///<param name="strConnection"></param>
        public DataAgent(string strConnection)
        {
            this.m_strConnectionString = strConnection;
        }
        #endregion
     
        #region OpenDataBase
        ///<summary>
        /// Open Database
        ///</summary>
        private void OpenDataBase()
        {
            try
            {
                this.m_objConnection = new OleDbConnection();
                this.m_objConnection.ConnectionString = this.m_strConnectionString;
                if (this.m_objConnection.State != ConnectionState.Open)
                {
                    this.m_objConnection.Open();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion
     
        #region CloseDataBase
        ///<summary>
        /// Close Database
        ///</summary>
        private void CloseDataBase()
        {
            if (this.m_objConnection != null)
            {
                if (this.m_objConnection.State == ConnectionState.Open)
                {
                    this.m_objConnection.Close();
                }
            }
        }
        #endregion
     
        #region GetDataView
        ///<summary>
        /// Execute the sql and return the default table view
        ///</summary>
        ///<param name="strSelectString">Select String</param>
        ///<returns>DataView of the DataTable</returns>
        public DataView GetDataView(string strSqlStat)
        {
            try
            {
                this.OpenDataBase();
                OleDbDataAdapter objDataAdapter = new OleDbDataAdapter(strSqlStat.Trim(), this.m_objConnection);
                DataSet objDataSet = new DataSet();
                objDataAdapter.Fill(objDataSet);
                return objDataSet.Tables[0].DefaultView;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                this.CloseDataBase();
            }
        }
        #endregion
    }
    3.Business的具体实现:
    建立名为Base的类,此类作为其他事务类的基类,其中定义了一个DataAgent的实例。其他所有的Business类都从该改类派生。
    在该类中添加对DataAgent的引用,使所有的事务类都能使用DataAgent中的方法。
    Base.cs源代码:
    public abstract class Base
    {
        protected DataAgent OleDBAgent = new DataAgent("Provider=SQLOLEDB;Data Source=(local);DataBase=test;User ID=sa;PWD=");
    }
    准备好了数据操作层和事务层的基类,底下就可以正式地开始业务逻辑类的开发了,如有一个显示新闻的类News,其中包含了一个GetNewsList()的方法,该方法用来获取所有的新闻标题列表,代码如下:
    public class News : Base
    {
        public DataView GetNewsList()
        {
            string strSql;
            strSql = "";
            strSql += " SELECT Top 10 NewsId,NewsTitle ";
            strSql += " FROM Tb_News";
            strSql += " WHERE NewsEnable = 1";
            strSql += " ORDER BY NewsId ";
            return OleDBAgent.GetDataView(strSql);
        }
    }
    由于数据库结构比较简单,在此就不再给出详细的表结构。
    4.UI层对Business中接口的调用
    首先,在窗体Form1中添加对News类的引用。
    然后,在窗体Form1中添加一个(DataGridView)dgNews用来显示新闻列表。
    在窗体的Form1_Load方法中添加如下代码:
    private void Form1_Load(object sender, EventArgs e)
    {
        News objNews = new News();
        this.dgNews.DataSource = objNews.GetNewsList();
    }
      

  3.   

    可以考虑使用 静态方法或属性 来生成或指定一个连接不过个人还是建议现用现new
      

  4.   

    共用类。
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using System.Data.OleDb;namespace School
    {
        static class Program
        {
            /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
        public class LinkDataBase
        {
            private string strSQL;
            private string oleSQL;
            //与SQL Server的连接字符串设置
            
            private string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\Work\\考勤统计\\att2000.mdb;Persist Security Info=True";
            private string oleconnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Work\考勤统计\att2000.mdb;Persist Security Info=True";
            //与数据库的连接
            private SqlConnection myConnection;
            private OleDbConnection oleConnection;        private SqlCommandBuilder sqlCmdBld;
            private DataSet ds = new DataSet();
            private SqlDataAdapter da;
            private OleDbDataAdapter oleda;        public LinkDataBase()
            {
                //
                // TODO: 在此处添加构造函数逻辑
                //
            }        /////////////////////////////////  操作脱机数据库(创建了该类的实例时直接用)  /////////////////////////////////////////////////////        //根据输入的SQL语句检索数据库数据
            public DataSet SelectDataBase(string tempStrSQL, string tempTableName)
            {
                this.strSQL = tempStrSQL;
                this.myConnection = new SqlConnection(connectionString);
                this.da = new SqlDataAdapter(this.strSQL, this.myConnection);
                this.ds.Clear();
                this.da.Fill(ds, tempTableName);
                return ds;//返回填充了数据的DataSet,其中数据表以tempTableName给出的字符串命名
            }        //数据库数据更新(传DataSet和DataTable的对象)
            public DataSet UpdateDataBase(DataSet changedDataSet, string tableName)
            {
                this.myConnection = new SqlConnection(connectionString);
                this.da = new SqlDataAdapter(this.strSQL, this.myConnection);
                this.sqlCmdBld = new SqlCommandBuilder(da);
                this.da.Update(changedDataSet, tableName);
                return changedDataSet;//返回更新了的数据库表
            }        /////////////////////////////////  直接操作数据库(未创建该类的实例时直接用)  /////////////////////////////////////////////////////        //检索数据库数据(传字符串,直接操作数据库)
            public DataTable SelectDataBase(string tempStrSQL)
            {
                this.myConnection = new SqlConnection(connectionString);
                DataSet tempDataSet = new DataSet();
                this.da = new SqlDataAdapter(tempStrSQL, this.myConnection);
                this.da.Fill(tempDataSet);
                return tempDataSet.Tables[0];
            }        public DataTable OleSelectDataBase(string tempOleStr)
            {
                this.oleConnection = new OleDbConnection(oleconnectionString);
                DataSet tempDataSet = new DataSet();
                this.oleda = new OleDbDataAdapter(tempOleStr, this.oleConnection);
                this.oleda.Fill(tempDataSet);
                return tempDataSet.Tables[0];
            }        //数据库数据更新(传字符串,直接操作数据库)
            public int UpdateDataBase(string tempStrSQL)
            {
                this.myConnection = new SqlConnection(connectionString);
                //使用Command之前一定要先打开连接,后关闭连接,而DataAdapter则会自动打开关闭连接
                myConnection.Open();
                SqlCommand tempSqlCommand = new SqlCommand(tempStrSQL, this.myConnection);
                int intNumber = tempSqlCommand.ExecuteNonQuery();//返回数据库中影响的行数
                myConnection.Close();
                return intNumber;
            }        public int OleUpdateDataBase(string tempOleStr)
            {
                this.oleConnection = new OleDbConnection(oleconnectionString);
                oleConnection.Open();
                OleDbCommand tempOleCommand = new OleDbCommand(tempOleStr, this.oleConnection);
                int intNumber = tempOleCommand.ExecuteNonQuery();
                oleConnection.Close();
                return intNumber;
            }
        }
    }
      

  5.   

    刚才贴的有点问题using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using System.Data.OleDb;
    using Excel = Microsoft.Office.Interop.Excel;namespace CheckInOut
    {
        static class Program
        {
            /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                //Application.Run(new Login());
                Application.Run(new Form1());
            }
        }
        public class LinkDataBase
        {
            //static public string svrname, sa, pwd;
            private string strSQL;
            //与SQL Server的连接字符串设置
            public string connectionString ;
            //与数据库的连接
            private SqlConnection myConnection;        private SqlCommandBuilder sqlCmdBld;
            private DataSet ds = new DataSet();
            private SqlDataAdapter da;        public LinkDataBase()
            {
                //
                // TODO: 在此处添加构造函数逻辑
                //
            }        /////////////////////////////////  操作脱机数据库(创建了该类的实例时直接用)  /////////////////////////////////////////////////////        //根据输入的SQL语句检索数据库数据
            public DataSet SelectDataBase(string tempStrSQL, string tempTableName)
            {
                this.strSQL = tempStrSQL;
                this.myConnection = new SqlConnection(connectionString);
                this.da = new SqlDataAdapter(this.strSQL, this.myConnection);
                this.ds.Clear();
                this.da.Fill(ds, tempTableName);
                return ds;//返回填充了数据的DataSet,其中数据表以tempTableName给出的字符串命名
            }        //数据库数据更新(传DataSet和DataTable的对象)
            public DataSet UpdateDataBase(DataSet changedDataSet, string tableName)
            {
                this.myConnection = new SqlConnection(connectionString);
                this.da = new SqlDataAdapter(this.strSQL, this.myConnection);
                this.sqlCmdBld = new SqlCommandBuilder(da);
                this.da.Update(changedDataSet, tableName);
                return changedDataSet;//返回更新了的数据库表
            }        /////////////////////////////////  直接操作数据库(未创建该类的实例时直接用)  /////////////////////////////////////////////////////        //检索数据库数据(传字符串,直接操作数据库)
            public DataTable SelectDataBase(string tempStrSQL)
            {                this.myConnection = new SqlConnection(connectionString);
                    DataSet tempDataSet = new DataSet();
                    this.da = new SqlDataAdapter(tempStrSQL, this.myConnection);
                    this.da.Fill(tempDataSet);
                    return tempDataSet.Tables[0];
           
            }        //数据库数据更新(传字符串,直接操作数据库)
            public int UpdateDataBase(string tempStrSQL)
            {
                this.myConnection = new SqlConnection(connectionString);
                //使用Command之前一定要先打开连接,后关闭连接,而DataAdapter则会自动打开关闭连接
                myConnection.Open();
                SqlCommand tempSqlCommand = new SqlCommand(tempStrSQL, this.myConnection);
                int intNumber = tempSqlCommand.ExecuteNonQuery();//返回数据库中影响的行数
                myConnection.Close();
                return intNumber;
            }
        }