C#数据库与单独的类连接。 [英] C# Database Connection with a separate class.

查看:52
本文介绍了C#数据库与单独的类连接。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个连接到MS Access数据库的应用程序。但是我还使用了另一个包含数据库连接变量的类。它如下所示



I have created an application that connects to an MS Access Database. But I have also used an another class that holds the database connection variables. it is as the following

using System.Text;
using System.Data.OleDb;
using System.Data.DataTable;

namespace Lanka_Lab
{
    public class dbConnect
    {
        public OleDbConnection oleDbConnect;
        public OleDbDataAdapter oleDbAdapt;
        public OleDbCommand oleDbComm;
        

    }
}





但是我要连接到的UI数据库在另一个类中





But the UI that I want to connect to the database is in another class

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;


namespace Lanka_Lab
{
    public partial class frmFulBldCuntDet : Form
    {
 
    }

}





我现在的问题是我想用dbconnect类中的变量设置一些值拥有UI的类。



换句话说,dbconnect类中的变量将在整个项目中使用,我创建该类作为VB.Net中的通用模块来保存全局变量。



尝试将值设置为dbconnect类中的变量时,我找不到任何错误。请帮助我!



Chiransj



My problem is now I want to set some values to the variables in the dbconnect class using the class that holds the UI.

In another words the variables are in the dbconnect class will be used whole over the project and I created that class as a general module in VB.Net to hold global variables.

I cannot find any errors when try to set values to the variables in the dbconnect class. Please help me!

Chiransj

推荐答案

像这样修改你的课程



Modify your class like this

public class dbConnect
{
    public OleDbConnection oleDbConnect;
    public OleDbDataAdapter oleDbAdapt;
    public OleDbCommand oleDbComm;

    private static dbConnect dbConn=null;
    public static dbConnect GetConnection()
    {
        if (dbConn == null)
        {
            dbConn = new dbConnect();
        }
        return dbConn;
    }

}





现在,您将在整个项目中获得相同的dbConnect实例。您为变量设置的值将一直保留到应用程序退出。



在您想要dbConnect实例的任何地方使用以下代码。



Now you will get the same instance of dbConnect throughout the project. The values you set for the variables will retain till application exit.

Use the following code wherever you want the instance of dbConnect.

dbConnect db = dbConnect.GetConnection();


SqlBulkCopy Bcp;

   public SqlConnection Con;
   public SqlCommand Cmd;
   public SqlDataReader Dr;
   public DataSet Ds;
   SqlDataAdapter Add;
   SqlTransaction Tran;
   //public event  SqlRowsCopied(  Object  Sender,  System.Data.SqlClient.SqlRowsCopiedEventArgs e);
   public ClsConnection()
   {
       Con = new SqlConnection();

       Con.ConnectionString = ConfigurationManager.ConnectionStrings["PropertyConnectionString"].ConnectionString;


       Con.Open();
   }



   public void cancel()
   {
       Cmd.Cancel();
   }
   public void class1(string SqlCon)
   {
       Con = new SqlConnection();
       Con.ConnectionString = SqlCon;
       Con.Open();
   }
   public bool OPen()
   {
       if (Con.State != ConnectionState.Open)
       {
           try
           {
               Con.Open();
               return true;
           }
           catch (Exception ex)
           {
               return false;
           }
       }
       else
           return true;

   }

   public void Bulkcopy(string Destination, DataTable DataSource, int NotifyAfter)
   {
       try
       {
           Bcp = new SqlBulkCopy(Con);
           Bcp.BulkCopyTimeout = 300;
           Bcp.DestinationTableName = Destination;
           Bcp.NotifyAfter = NotifyAfter;
           Bcp.WriteToServer(DataSource);
       }
       catch (Exception ex)
       {
           throw (ex);
       }
   }


   public int MaxValue(string Table, string Column, string DefaultValue)
   {
       return (MaxValue(Table, Column, DefaultValue, ""));
   }

   public int MaxValue(string Table, string Column, string DefaultValue, string Condition)
   {
       return (Convert.ToInt32(ExecuteScalar("Select isnull(max(" + Column + ")," + DefaultValue + ") from " + Table + (Condition == "" ? "" : " Where ") + Condition)));


   }


   public DataRow FillRow(string Sqlstr)
   {
       CommandText(Sqlstr);
       SqlDataAdapter Ad = new SqlDataAdapter();
       Ad.SelectCommand = Cmd;
       DataSet LDs = new DataSet();
       Ad.Fill(LDs, "Table");
       if (LDs.Tables["Table"].Rows.Count > 0)
           return ((LDs.Tables["Table"].Rows[0]));
       else
           return (null);

   }
   public void FillDataSet(DataSet LDataSet, string Sqlstr, string TableName)
   {
       CommandText(Sqlstr);
       SqlDataAdapter Ad = new SqlDataAdapter();

       Ad.SelectCommand = Cmd;
       Ad.Fill(LDataSet, TableName);
   }
   public void ClearDataSet(DataSet LDataSet)
   {
       LDataSet.Clear();
   }
   public void BeginTrans()
   {
       Tran = Con.BeginTransaction();
   }
   public void CommitTrans()
   {
       Tran.Commit();
   }
   public void RollBackTrans()
   {
       Tran.Rollback();
   }
   public void CommandText(string SqlStr)
   {
       Cmd = new SqlCommand();
       Cmd.CommandText = SqlStr;
       Cmd.Connection = Con;
       Cmd.Transaction = Tran;
   }
   public static bool ExecuteNonQuery(string QueryString, params SqlParameter[] arrParam)
   {
       string qry = "";
       SqlConnection Con = new SqlConnection();


       Con.ConnectionString = ConfigurationManager.ConnectionStrings["PropertyConnectionString"].ConnectionString;
       Con.Open();

           if (arrParam != null)
           {

               qry = QueryString;

               SqlCommand cmd = new SqlCommand(qry, Con);

               cmd.Parameters.AddRange(arrParam);

               cmd.ExecuteNonQuery();


               cmd.Dispose();
               Con.Close();

               return true;


           }


       return false;

   }

   public static string changeNameloop(int len)
   {

       System.Threading.Thread.Sleep(100);
       string _allowedChars = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
       //string _allowedChars = "0123456789";
       Random randNum = new Random();
       char[] chars = new char[len];
       int allowedCharCount = _allowedChars.Length;
       for (int i = 0; i < len; i++)
       {
           chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
       }

       return new string(chars);

   }
   public int ExecuteNonQuery(string SqlStr)
   {
       CommandText(SqlStr);
       return (Cmd.ExecuteNonQuery());
   }

   public object ExecuteScalar(string SqlStr)
   {
       CommandText(SqlStr);
       return (Cmd.ExecuteScalar());

   }

   public int ExecuteLineReader(string SqlStr)
   {
       CommandText(SqlStr);
       Dr = Cmd.ExecuteReader();
       if (Dr.Read())
           return (1);
       else
           return (0);

   }
   public DataTable FillTable(string Sqlstr, string TableName)
   {
       CommandText(Sqlstr);
       SqlDataAdapter Ad = new SqlDataAdapter();
       Ad.SelectCommand = Cmd;
       Ds = new DataSet();
       Ad.Fill(Ds, TableName);
       return (Ds.Tables[TableName]);
   }
   public DataTable ExecuteProc(string ProcName, params     object[] Parameter)
   {
       CommandText(ProcName);
       Cmd.CommandType = CommandType.StoredProcedure;
       int i = 0;
       while (i < Parameter.Length)
       {
           Cmd.Parameters.Add(Cmd.CreateParameter());
           Cmd.Parameters[i].ParameterName = Convert.ToString(Parameter[i]);
           Cmd.Parameters[i].Value = Parameter[i * 2 + 1];
           i = i + 1;
       }
       SqlDataAdapter Ad = new SqlDataAdapter();
       Ad.SelectCommand = Cmd;
       Ds = new DataSet();
       Ad.Fill(Ds, ProcName);
       return (Ds.Tables[ProcName]);
   }

   public void CloseReader()
   {
       Dr.Close();
   }

   public void Close()
   {
       if (Con.State != ConnectionState.Closed)
           Con.Close();

   }


这篇关于C#数据库与单独的类连接。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆