天天看點

C#資料庫操作執行個體

 最近學習了C#,一個執行個體程式,對Access資料庫的單個表檔案進行操作的例子。其中包括了對資料的查詢,添加,删除,更新。其中用到的内容總結如下:

(1)程式類劃分:User類----資料類,與資料庫中的myUser表相對應

                               ConnectDatabase類-----連接配接字元串生成,負責生成連接配接字元串

                               ManageUser類------負責各項操作事物,包括添加,删除,查詢,更新等功能的實作

(2)出于練習的目的,采用了ListView控件顯示所有資料。用到了添加,删除等部分的代碼。

(3)部分代碼

ConnectDatabase類的代碼:

 public class ConnectDatabase

 {

   public virtual string GetConnectionString()

  {

   //Access資料庫連接配接字元串

   string connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..//..//data//db.mdb";

   return connstr;

  }

 }

User類的代碼:

using System;

using System.Windows.Forms;

namespace DataManage

{

 /// <summary>

 /// Description of User.

 /// </summary>

 public class User

 {

  #region Field Members

        private int m_iD;        

        private string m_name;        

        private string m_password;        

        private float m_salary;        

        private string m_address;        

        private DateTime m_birthday;        

        private string m_memo;        

        #endregion

         #region Property Members

         // [PrimaryKey(PrimaryKeyType.Identity, "ID")]

         public virtual int ID

        {

            get

            {

                return this.m_iD;

            }

            set

            {

             this.m_iD=value;

            }

        }

          // [Property("Name")]

         public virtual string Name

        {

            get

            {

                return this.m_name;

            }

            set

            {

                this.m_name = value;               

            }

        }

        //[Property("Password")]

         public virtual string Password

        {

            get

            {

                return this.m_password;

            }

            set

            {

                this.m_password = value;               

            }

        }

        //[Property("Salary")]

         public virtual float Salary

        {

            get

            {

                return this.m_salary;

            }

            set

            {

                this.m_salary = value;               

            }

        }

        //[Property("Address")]

         public virtual string Address

        {

            get

            {

                return this.m_address;

            }

            set

            {

                this.m_address = value;               

            }

        }

        //[Property("Birthday")]

         public virtual DateTime Birthday

        {

            get

            {

                return this.m_birthday;

            }

            set

            {

             if(value>=Convert.ToDateTime("1900-1-1")&&value.Year<=DateTime.Now.Year)

                  this.m_birthday = value;

             else

              MessageBox.Show("生日設定錯誤,超出範圍!");

            }

        }

        //[Property("Memo")]

         public virtual string Memo

        {

            get

            {

                return this.m_memo;

            }

            set

            {

                this.m_memo = value;               

            }

        }

        #endregion

  public User()

  {

  }

  public User(int id,string name,string password,float salary,string address,DateTime birthday,string memo)

  {

   this.m_iD=id;

   this.m_name=name;

   this.m_password=password;

   this.m_salary=salary;

   this.m_address=address;

   this.m_birthday=birthday;

   this.m_memo=memo;

  }

 }

}

MangeUser類的代碼:

using System;

using System.Data;

using System.Data.OleDb;

using System.Collections;

namespace DataManage

{

 /// <summary>

 /// Description of ManageUser.

 /// </summary>

 public class ManageUser

 {

  public ManageUser()

  {

  }

  //取得連接配接

  public OleDbConnection getConn()

  {

   ConnectDatabase connstr=new ConnectDatabase();

   string connStr=connstr.GetConnectionString();

   OleDbConnection oledb=new OleDbConnection(connStr);

   return oledb;

  }

  //依據姓名獲得使用者資訊

  public User getUserFromName(string Searchname)

  {

   User tempUser=new User();

   try

   {

    OleDbConnection oleconn=getConn();//資料庫連接配接

    string strSel="select * from MyUser where Name='"+ Searchname+"'";//查詢語句

    OleDbCommand myCommand=new OleDbCommand(strSel,oleconn);//查詢指令

    oleconn.Open();//打開資料庫連接配接

    OleDbDataReader reader;

    reader=myCommand.ExecuteReader();//執行查詢指令,傳回記錄集

    if(reader.Read())

    {

     tempUser.ID=(int)reader["ID"];

     tempUser.Name=reader["Name"].ToString();

     tempUser.Salary=(float)reader["Salary"];

     tempUser.Password=reader["Password"].ToString();

     tempUser.Memo=reader["Memo"].ToString();

     tempUser.Birthday=(DateTime)reader["Birthday"];

     tempUser.Address=reader["Address"].ToString();

    }

    else

    {

     throw new Exception("沒有記錄");

    }

    reader.Close();//關閉記錄集

    oleconn.Close();//關閉連接配接

   }

   catch(Exception e)

   {

    throw new Exception("打開資料庫出錯"+e.Message);

   }

   return tempUser;

  }

//擷取所有使用者的資訊

  public ArrayList getAllUser()

  {

   ArrayList arr=new ArrayList();

   try

   {

    OleDbConnection oleconn=getConn();//資料庫連接配接

    string strSel="select * from MyUser";//查詢語句

    OleDbCommand myCommand=new OleDbCommand(strSel,oleconn);//查詢指令

    oleconn.Open();//打開資料庫連接配接

    OleDbDataReader reader;

    reader=myCommand.ExecuteReader();//執行查詢指令,傳回記錄集

    while(reader.Read())

    {

     User tempUser=new User();

     tempUser.ID=(int)reader["ID"];

     tempUser.Name=reader["Name"].ToString();

     tempUser.Salary=(float)reader["Salary"];

     tempUser.Password=reader["Password"].ToString();

     tempUser.Memo=reader["Memo"].ToString();

     tempUser.Birthday=(DateTime)reader["Birthday"];

     tempUser.Address=reader["Address"].ToString();

     arr.Add(tempUser);

    }

    reader.Close();//關閉記錄集

    oleconn.Close();//關閉連接配接

   }

   catch(Exception e)

   {

    throw new Exception("打開資料庫出錯"+e.Message);

   }

   return arr;

  }

  public void InsertUser(User insertuser)

  {

   try

   {

    OleDbConnection oleconn=getConn();//資料庫連接配接

    oleconn.Open();//打開資料庫連接配接

    string strSel="insert into [MyUser]([Name],[Password],[Salary],[Address],[Birthday],[Memo])"; //插入語句

    strSel+=" values('"+insertuser.Name+"','"+insertuser.Password+"',"+insertuser.Salary.ToString();

    strSel+=",'"+insertuser.Address+"',#"+insertuser.Birthday.ToString()+"#,'"+insertuser.Memo+"')";

    OleDbCommand myCommand=new OleDbCommand(strSel,oleconn);//查詢指令

    myCommand.ExecuteNonQuery();

    oleconn.Close();//關閉連接配接

   }

   catch(Exception e)

   {

    throw new Exception("打開資料庫出錯"+e.Message);

   }

  }

  public void DeleteUser(int m_id)

  {

   try

   {

    OleDbConnection oleconn=getConn();

    oleconn.Open();

    string strSel="Delete From [Myuser] where ID="+m_id.ToString();

    OleDbCommand myCommand=new OleDbCommand(strSel,oleconn);

    myCommand.ExecuteNonQuery();

    oleconn.Close();

   }

   catch(Exception e)

   {

    throw new Exception("删除記錄出錯"+e.Message);

   }

  }

  public string GetInsertSQL(User insertuser)

  {

   string strSel="insert into [MyUser]([Name],[Password],[Salary],[Address],[Birthday],[Memo])"; //插入語句

    strSel+=" values('"+insertuser.Name+"','"+insertuser.Password+"',"+insertuser.Salary.ToString();

    strSel+=",'"+insertuser.Address+"',#"+insertuser.Birthday.ToString()+"#,'"+insertuser.Memo+"')";

    return strSel;

  }

  public string GetDelUserSQL(int m_id)

  {

   string strSel="Delete From [Myuser] where ID="+m_id.ToString();

   return strSel;

  }

  public string GetUserFromNameSQL(string Name)

  {

   string strSel="select * from MyUser where Name='"+ Name+"'";//查詢語句

   return strSel;

  }

  public ArrayList exeSelect(string SQLSel)

  {

   ArrayList arr=new ArrayList();

   try

   {

    OleDbConnection oleconn=getConn();//資料庫連接配接

    string strSel="";

    if(SQLSel=="")

       strSel="select * from MyUser";//查詢語句

    else

     strSel=SQLSel;

    OleDbCommand myCommand=new OleDbCommand(strSel,oleconn);//查詢指令

    oleconn.Open();//打開資料庫連接配接

    OleDbDataReader reader;

    reader=myCommand.ExecuteReader();//執行查詢指令,傳回記錄集

    while(reader.Read())

    {

     User tempUser=new User();

     tempUser.ID=(int)reader["ID"];

     tempUser.Name=reader["Name"].ToString();

     tempUser.Salary=(float)reader["Salary"];

     tempUser.Password=reader["Password"].ToString();

     tempUser.Memo=reader["Memo"].ToString();

     tempUser.Birthday=(DateTime)reader["Birthday"];

     tempUser.Address=reader["Address"].ToString();

     arr.Add(tempUser);

    }

    reader.Close();//關閉記錄集

    oleconn.Close();//關閉連接配接

   }

   catch(Exception e)

   {

    throw new Exception("打開資料庫出錯"+e.Message);

   }

   return arr;

  }

  public void exeNoQuery(string strSQL)

  {

   string strSel;

    if(strSQL!="")

    {

     strSel=strSQL;

    }

    else

    {

     return;

    }

   try

   {

    OleDbConnection oleconn=getConn();//資料庫連接配接

    oleconn.Open();//打開資料庫連接配接

//    string strSel="insert into [MyUser]([Name],[Password],[Salary],[Address],[Birthday],[Memo])"; //插入語句

//    strSel+=" values('"+insertuser.Name+"','"+insertuser.Password+"',"+insertuser.Salary.ToString();

//    strSel+=",'"+insertuser.Address+"',#"+insertuser.Birthday.ToString()+"#,'"+insertuser.Memo+"')";

    OleDbCommand myCommand=new OleDbCommand(strSel,oleconn);//查詢指令

    myCommand.ExecuteNonQuery();

    oleconn.Close();//關閉連接配接

   }

   catch(Exception e)

   {

    throw new Exception("打開資料庫出錯"+e.Message);

   }

  }

 }

}

源代碼http://download.csdn.net/user/jh2005