C# 向学生添加时间表的DB访问代码

C# 向学生添加时间表的DB访问代码,c#,sql,C#,Sql,将时间表的DB访问代码添加到my Student class以进行选择,并从时间表表中插入。Select代码应该放在selectDB()函数中,该函数在DB中查找学生。插入代码将放在addSection()方法中 因此,我向学生添加了SQL以调出该部分,但当我运行windows代码时,该部分不会显示 学生: class Student : Person { private int iD; private String password; p

将时间表的DB访问代码添加到my Student class以进行选择,并从时间表表中插入。Select代码应该放在selectDB()函数中,该函数在DB中查找学生。插入代码将放在addSection()方法中

因此,我向学生添加了SQL以调出该部分,但当我运行windows代码时,该部分不会显示

学生:

class Student : Person
    {
        private int iD;
        private String password;
        private String eMail;
        private double gpa;
        private String message;


        public Student() : base()
        {
            this.iD = 0;
            this.password = "";
            this.eMail = "";
            this.gpa = 0;
        }
        public Student(int i, String pa, String eM, int gp) : base()
        {
            this.iD = i;
            this.password = pa;
            this.eMail = eM;
            this.gpa = gp;
            InsertDB();
        }
          public Student(int iD)
        {
            SelectDB(iD);
        }
                //++++++++++++++++  DATABASE Data Elements +++++++++++++++++
        public System.Data.OleDb.OleDbDataAdapter OleDbDataAdapter;
        public System.Data.OleDb.OleDbCommand OleDbSelectCommand;
        public System.Data.OleDb.OleDbCommand OleDbInsertCommand;
        public System.Data.OleDb.OleDbCommand OleDbUpdateCommand;
        public System.Data.OleDb.OleDbCommand OleDbDeleteCommand;
        public System.Data.OleDb.OleDbConnection OleDbConnection;
        public string cmd;

        public void DBSetup(){
        // +++++++++++++++++++++++++++  DBSetup function +++++++++++++++++++++++++++
        // This DBSetup() method instantiates all the DB objects needed to access a DB, 
        // including OleDbDataAdapter, which contains 4 other objects(OlsDbSelectCommand, 
        // oleDbInsertCommand, oleDbUpdateCommand, oleDbDeleteCommand.) And each
        // Command object contains a Connection object and an SQL string object.
            OleDbDataAdapter = new System.Data.OleDb.OleDbDataAdapter();
            OleDbSelectCommand = new System.Data.OleDb.OleDbCommand();
            OleDbInsertCommand = new System.Data.OleDb.OleDbCommand();
            OleDbUpdateCommand = new System.Data.OleDb.OleDbCommand();
            OleDbDeleteCommand = new System.Data.OleDb.OleDbCommand();
            OleDbConnection = new System.Data.OleDb.OleDbConnection();


            OleDbDataAdapter.DeleteCommand = OleDbDeleteCommand;
            OleDbDataAdapter.InsertCommand = OleDbInsertCommand;
            OleDbDataAdapter.SelectCommand = OleDbSelectCommand;
            OleDbDataAdapter.UpdateCommand = OleDbUpdateCommand;


OleDbConnection.ConnectionString = "Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Reg"+
"istry Path=;Jet OLEDB:Database L" + 
"ocking Mode=1;Data Source=c:\\RegistrationMDB.accdb;J" + 
"et OLEDB:Engine Type=5;Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:System datab" + 
"ase=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Mode=S" + 
"hare Deny None;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet " + 
"OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repai" + 
"r=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1";

        }

        public void SelectDB(int id) 
        { //++++++++++++++++++++++++++  SELECT +++++++++++++++++++++++++
            DBSetup();
            cmd = "Select * from Students where ID = " + iD;
            OleDbDataAdapter.SelectCommand.CommandText = cmd;
            OleDbDataAdapter.SelectCommand.Connection = OleDbConnection;
            Console.WriteLine(cmd);
            try  {
                    OleDbConnection.Open();
                    System.Data.OleDb.OleDbDataReader dr;
                    dr = OleDbDataAdapter.SelectCommand.ExecuteReader();

                    dr.Read();
                    id=iD;
                    setPassword(dr.GetValue(1)+"");
                    setEMail(dr.GetValue(2)+"");

                    setGpa(Double.Parse(dr.GetValue(3)+""));
            }
            catch (Exception ex) 
            {
                Console.WriteLine(ex);
            }
            finally 
            {
                OleDbConnection.Close();
            }                    
        }

        public void InsertDB() {
        // +++++++++++++++++++++++++++  INSERT +++++++++++++++++++++++++++++++

            DBSetup();
            cmd = "INSERT into Students values(" + getID() + "," +
                             "'" + getPassword() + "'," +
                             "'" + getEMail() + "'," +
                            "'" + getGpa() +  ")";

            OleDbDataAdapter.InsertCommand.CommandText = cmd;
            OleDbDataAdapter.InsertCommand.Connection = OleDbConnection;
            Console.WriteLine(cmd);
            try  
            {
                OleDbConnection.Open();
                int n = OleDbDataAdapter.InsertCommand.ExecuteNonQuery();
                if (n==1)
                    Console.WriteLine("Data Inserted");
                else
                    Console.WriteLine("ERROR: Inserting Data");
            }
            catch (Exception ex) 
            {
                Console.WriteLine(ex);
            }
            finally 
            {
                OleDbConnection.Close();
            }                
        }
        public void updateDB() 
        {
            //++++++++++++++++++++++++++  UPDATE  +++++++++++++++++++++++++

            cmd = "Update Students set ID = '" + getID() + "'," + 
                        "Password = '" + getPassword() +    "', " +
                        "Email = '" + getEMail() + "', " +
                         "GPA = " + getGpa();

            OleDbDataAdapter.UpdateCommand.CommandText = cmd;
            OleDbDataAdapter.UpdateCommand.Connection = OleDbConnection;
            Console.WriteLine(cmd);
            try  
            {
                OleDbConnection.Open();
                int n = OleDbDataAdapter.UpdateCommand.ExecuteNonQuery();
                if (n==1)
                    Console.WriteLine("Data Updated");
                else
                    Console.WriteLine("ERROR: Updating Data");
            }
            catch (Exception ex) 
            {
                Console.WriteLine(ex);
            }
            finally 
            {
                OleDbConnection.Close();
            }                    
        }

        public void deleteDB() 
        {
            //++++++++++++++++++++++++++  DELETE  +++++++++++++++++++++++++

            cmd = "Delete from Students where ID = " + getID();
            OleDbDataAdapter.DeleteCommand.CommandText = cmd;
            OleDbDataAdapter.DeleteCommand.Connection = OleDbConnection;
            Console.WriteLine(cmd);
            try  
            {
                OleDbConnection.Open();
                int n = OleDbDataAdapter.DeleteCommand.ExecuteNonQuery();
                if (n==1)
                    Console.WriteLine("Data Deleted");
                else
                    Console.WriteLine("ERROR: Deleting Data");
            }
            catch (Exception ex) 
            {
                Console.WriteLine(ex);
            }
            finally 
            {
                OleDbConnection.Close();
            }                    
        }





        public void setID(int iD)
        {
            this.iD = iD;
        }

        public void setPassword(String password)
        {
            this.password = password;
        }


        public void setEMail(String eMail)
        {
            this.eMail = eMail;
        }
        public void setGpa(double gpa)
        {
            this.gpa = gpa;
        }

        public int getID()
        {
            return iD;
        }


        public String getPassword()
        {
            return password;
        }



        public String getEMail()
        {
            return eMail;
        }

        public double getGpa()
        {
            return gpa;
        }
        public String getMessage()
        {
            return this.message;
        }

         public void displays(){
        System.Console.WriteLine("ID =  "+ getID());
        System.Console.WriteLine("Password =   "+ getPassword());
        System.Console.WriteLine("Email =  " + getEMail());
        System.Console.WriteLine("GPA =  " + getGpa());

    }


    }
附表:

public class Schedules
{
   private int studentID;
   private int cRN;
    public Schedules()
    {
        this.sections = new List<Section>();
    }

    /// <summary>
    /// collection of sections
    /// </summary>
    ICollection<Section> sections;

    /// <summary>
    /// Adds a section
    /// </summary>
    /// <param name="section"></param>
    public void Add(Section section)
    {
        if (section == null)
            throw new ArgumentNullException("section");

        this.sections.Add(section);
    }

    /// <summary>
    /// Drops a section
    /// </summary>
    /// <param name="section"></param>
    public void Drop(Section section)
    {
        if (section == null)
            throw new ArgumentNullException("section");
        this.sections.Remove(section);
    }



    public IEnumerable<Section> Display()
    {
        return this.sections;
    }


}
公共课程表
{
私立国际学生;
私人互联网;
公共附表()
{
this.sections=新列表();
}
/// 
///章节集
/// 
i采集断面;
/// 
///添加一个节
/// 
/// 
公共无效添加(第节)
{
if(节==null)
抛出新的异常(“节”);
本节。添加(节);
}
/// 
///删除一节
/// 
/// 
公共空投(第节)
{
if(节==null)
抛出新的异常(“节”);
本节。删除(节);
}
公共IEnumerable显示()
{
将此文件退还给我;
}
}

让您的数据库设置如下

using System.Data.OleDb; //import these at the top
using System.Data;

 public DataTable DBSetup(string query) 
 {
   public OleDbConnection con = new OleDbConnection
         (@"Provider=Microsoft.ACE.OLEDB.12.0;
         Data Source=c:\\RegistrationMDB.accdb;
         Persist Security Info=False;")
   OleDbDataAdapter da = new OleDbDataAdapter(query,con);
   DataTable dt = new DataTable();
   try
   {
     con.Open();
     da.Fill(dt);
   }
   catch (Exception ex)
   {
    Console.WriteLine(ex.Message);
   }
   finally 
   {
      if (con.State == ConnectionState.Open)
      { 
         con.Close();
      }
   }
return dt;
}
修改后,您可以在
SelectDB
中调用此
DBSetup
方法

     public void SelectDB(int id) 
     {              
            string Query = "Select * from Students where ID = " + id;
            try  
           {
                    DataTable dt= DBSetup(Query);
                    for(int i=0; i<dt.Rows.Count; i++)
                    {
                      setid(Convert.ToInt32(dt.Rows[i]["ID"]));
                      setPassword(dt.Rows[i]["password"].ToString());
                      setEMail(dt.Rows[i]["email"].ToString());
                      setGpa(Double.Parse(dt.Rows[i]["Gpa"]));
                      // ID,password,email,gpa these are column names
                      // you should replace with your column names
                    }
            }
            catch (Exception ex) 
            {
                Console.WriteLine(ex);
            }

        }

你的问题是什么?你得到了什么错误?这是其中之一,没有错误,但代码没有给我我想要发生的事情。我想让代码在selectDB()函数中有Select go,该函数在DB中查找学生,而Insert代码将在addSection()方法中。请检查selectDB()方法。。。这一行是错误的cmd=“Select*from Students where ID=“+ID;”;。。。。它必须是cmd=“Select*from Students where ID=“+ID;”----c#区分大小写,因此我认为在您搜索学生的情况下iD将为0。。。
 public void InsertDB() 
 {
       string Query = "INSERT into Students values(" + getID() + "," +
                         "'" + getPassword() + "'," +
                         "'" + getEMail() + "'," +
                        "'" + getGpa() +  ")";
   try
   {
     DBSetup(query);
     Console.WriteLine("Successfully inserted");
   }
    catch(Exception ex)
   {
     Console.WriteLine(ex.Message);
   }
 }