List Class Schedule for Students - c#

I finished my student schedule class turned it in, and my professor returned my work proclaiming that "Schedule is a list class, not just studentid and crn"
What does he mean by this? How do I fix it?
using System;
using System.Collections.Generic;
using System.Text;
namespace Schedule
{
class Schedule
{
private int studentID;
private int cRN;
public Schedule() {
this.studentID = 0;
this.cRN = 0;
}
//++++++++++++++++ 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:\Users\Tina\Desktop\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 studentID)
{ //++++++++++++++++++++++++++ SELECT +++++++++++++++++++++++++
DBSetup();
cmd = "Select * from Courses where StudentID = " + studentID;
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();
setStudentID(Int32.Parse(dr.GetValue(1)+""));
setCRN(Int32.Parse(dr.GetValue(1)+""));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleDbConnection.Close();
}
}
public void InsertDB() {
// +++++++++++++++++++++++++++ INSERT +++++++++++++++++++++++++++++++
DBSetup();
cmd = "INSERT into StudentSchedule values(" + getStudentID() + "," +
"'" + getCRN() + ")";
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 StudentSchedule set StudentID = '" + getStudentID() + "'," +
"CRN = '" + getCRN();
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 StudentSchedule where StudentID = " + getStudentID();
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 setStudentID(int studentID) {
this.studentID = studentID;
}
public void setCRN(int cRN) {
this.cRN = cRN;
}
public int getStudentID() {
return studentID;
}
public int getCRN() {
return cRN;
}
public void display(){
System.Console.WriteLine("Student ID = "+ getStudentID());
System.Console.WriteLine("CRN = "+ getCRN());
}
}
}
here is the student schedule
This is the sections.

You should probably ask your professor, but I would say that you should have a Student class and Schedule would have a property that is List<Student>. Also you don't / shouldn't make all those OleDb* public.

You should start by thinking about what a schedule is - a list of events. If you look at your SelectDB, you only ever have the ability to store one student and one course. But if you look at your select statement, Select * from Courses WHERE StudentId = whatever, there's a possibility that multiple rows can be returned from the query.
What you should have is your schedule class defined with a List<Courses> and whatever properties you need.
public class Schedule
{
private int studentID;
private List<Course> courseList;
}
And your course object could look something like:
public class Course
{
public int courseId;
public int studentId;
public int name;
}
This should get you moving in the right direction.

Related

C# Data Grid keeps populating with old data

I am a noob playing around with basic read, write and delete queries through C# into a MySQL Database. I am however stuck at the initial reading part. It appears that while reading the data from MySQL into a Data Grid View goes fine, however upon attempting to refresh the data it keeps populating the Grid with the same data (See photo) Unsure if this is originating from the Data Grid or the MySQL Dataset.
public partial class CBMain : Form
{
Connection con = new Connection();
private static ArrayList Listid = new ArrayList();
private static ArrayList ListItem = new ArrayList();
private static ArrayList ListDescription = new ArrayList();
private static ArrayList ListSerial = new ArrayList();
private static ArrayList ListQuantity = new ArrayList();
public CBMain()
{
InitializeComponent();
}
private void GetData()
{
try
{
con.Open();
string query = "select id, Item, Description, Serial, QuantityIn from TB_CB_StockIn";
MySqlDataReader row;
row = con.ExecuteReader(query);
if (row.HasRows)
{
while (row.Read())
{
Listid.Add(row["id"].ToString());
ListItem.Add(row["Item"].ToString());
ListDescription.Add(row["Description"].ToString());
ListSerial.Add(row["Serial"].ToString());
ListQuantity.Add(row["QuantityIn"].ToString());
}
}
else
{
MessageBox.Show("Data not found");
}
con.Close();
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
private void updateDatagrid()
{
for (int i = 0; i < Listid.Count; i++)
{
DataGridViewRow newRow = new DataGridViewRow();
newRow.CreateCells(DGV_Stock);
newRow.Cells[0].Value = Listid[i];
newRow.Cells[1].Value = ListItem[i];
newRow.Cells[2].Value = ListDescription[i];
newRow.Cells[3].Value = ListSerial[i];
newRow.Cells[4].Value = ListQuantity[i];
DGV_Stock.Rows.Add(newRow);
}
}
private void BT_Refresh_Click(object sender, EventArgs e)
{
DGV_Stock.DataSource = null;
DGV_Stock.Rows.Clear();
DGV_Stock.Refresh();
GetData();
if (Listid.Count > 0)
{
updateDatagrid();
}
else
{
MessageBox.Show("Data not found");
}
}
}
Connection :
class Connection
{
MySql.Data.MySqlClient.MySqlConnection conn;
static string host = "*******";
static string database = "*******";
static string userDB = "*******";
static string password = "*******";
public static string strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
public bool Open()
{
try
{
strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
conn = new MySqlConnection(strProvider);
conn.Open();
return true;
}
catch (Exception er)
{
MessageBox.Show("Connection Error ! " + er.Message, "Information");
}
return false;
}
public void Close()
{
conn.Close();
conn.Dispose();
}
public DataSet ExecuteDataSet(string sql)
{
try
{
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);
da.Fill(ds, "result");
return ds;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public MySqlDataReader ExecuteReader(string sql)
{
try
{
MySqlDataReader reader;
MySqlCommand cmd = new MySqlCommand(sql, conn);
reader = cmd.ExecuteReader();
return reader;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public int ExecuteNonQuery(string sql)
{
try
{
int affected;
MySqlTransaction mytransaction = conn.BeginTransaction();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
affected = cmd.ExecuteNonQuery();
mytransaction.Commit();
return affected;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return -1;
}
}
Initial Data Read in Red, then after Refresh keeps populating
You never clear arraylist data so it will appear multiple times your click. My suggestion you should learn how to use arraylist.
Anyway, you should use only one arraylist and create object class instead to store those fields.

Delete a table in the database mdb form

My goal for a project due is to get the Instructors to delete from the MS Access database table Instructor where ID = get id
Now I get an error on the form that says
Use of unassigned local variable 'iD' C:\Users\Tina\documents\visual studio 2013\Projects\Students\Students\DeleteInstructor.cs 29 24 Students
Instructor class:
class Instructor : Person
{
private int iD;
private String office;
private String eMail;
private String message;
public Instructor() : base()
{
this.iD = 0;
this.office = "";
this.eMail = "";
}
public Instructor(int i, String off, String eM) : base()
{
this.iD = i;
this.office = off;
this.eMail = eM;
InsertDB();
}
public Instructor(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 Instructors 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;
setOffice(dr.GetValue(1)+"");
setEMail(dr.GetValue(2)+"");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleDbConnection.Close();
}
} //end SelectDB()
public void InsertDB() {
// +++++++++++++++++++++++++++ INSERT +++++++++++++++++++++++++++++++
DBSetup();
cmd = "INSERT into Instructors values(" + getID() + "," +
"'" + getOffice() + "'," +
"'" + getEMail() + ")";
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 Instructors set ID = '" + getID() + "'," +
"Office = '" + getOffice() + "', " +
"EMail = '" + getEMail() +
" where ID = " + getID();
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();
}
} //end UpdateDB()
public void deleteDB(int iD)
{
//++++++++++++++++++++++++++ DELETE +++++++++++++++++++++++++
cmd = "Delete from Instructors 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 setOffice(String office)
{
this.office = office;
}
public void setEMail(String eMail)
{
this.eMail = eMail;
}
public int getID()
{
return iD;
}
public String getOffice()
{
return office;
}
public String getEMail()
{
return eMail;
}
public String getMessage()
{
return this.message;
}
public void displays(){
System.Console.WriteLine("ID = "+ getID());
System.Console.WriteLine("Office = "+ getOffice());
System.Console.WriteLine("Email = " + getEMail());
}
}
Form:
namespace Students
{
public partial class DeleteInstructor : Form
{
public DeleteInstructor()
{
InitializeComponent();
}
private void InstructorIDText_TextChanged(object sender, EventArgs e)
{
}
private void Delete_Click(object sender, EventArgs e)
{
int iD;
Instructor s = new Instructor(iD);
s.deleteDB(iD);
}
}
}
The error is pretty clear. You have not assigned a value to the variable iD. You need to set it before using it in your delete method.
private void Delete_Click(object sender, EventArgs e)
{
int iD = 1;
Instructor s = new Instructor(iD);
s.deleteDB(iD);
}
I have put "1" as an example here. It could be fetched from a control or a selection made by the user, basically some input received from the user.
The error is absolutely right. You are not assigning any value to the variable iD before calling it..
private void Delete_Click(object sender, EventArgs e)
{
int iD; // -> here it is unassigned
Instructor s = new Instructor(iD);
s.deleteDB(iD);
}
You should assign a value like
int iD = 0;
Or take value from somewhere like a DataGrid or TextBox or Combobox
int iD = Convert.ToInt32(textBox1.Text);

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll 90210

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
(provider: SQL Network Interfaces, error: 26 - Error Locating
Server/Instance Specified)
da.SelectCommand = cmd;
da.Fill(ds);
The code:
public string LogNotification { get; set; }
public bool ConfirmLogin(string id, string pw)
{
using (SqlConnection con = new SqlConnection("Data Source=C:\\RegistrationMDB.mdb"))
{
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT ID, PASSWORD FROM Students WHERE ID = #ID OR PASSWORD = #PASSWORD", con);
da.SelectCommand = cmd;
da.Fill(ds);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = id;
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = pw;
foreach (DataRow dr in ds.Tables[0].Rows)
{
iD = (dr["#ID"].ToString());
password = dr["#PASSWORD"].ToString();
}
if (iD == id && password == pw)
{
return true;
}
else
{
LogNotification = "ID/Password is incorrect";
return false;
}
}
}
Database Code;
//++++++++++++++++ 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.mdb;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(String 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();
}
}
Looking at your connection string, it appears that you are trying to directly open an MS Access database (.MDB) file using a SqlConnection object.
This raises a couple of issues.
It sounds like you don't have a correct connection string for your Access database. Here's a link to some suggestions of how to setup your connection string depending on the technology that you're using:
https://www.connectionstrings.com/access/
Also, as was mentioned below, it appears that you're using an incorrect connection type. Please see this related question for more information:
SQL connection string for microsoft access 2010 .accdb

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll 332

The Sql connection error starts at the Dataset ds as unable to get the data into the form:
using (SqlConnection con = new SqlConnection("Data Source=c:\\RegistrationMDB.accdb"))
{
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT ID, PASSWORD FROM Students WHERE ID = #ID OR PASSWORD = #PASSWORD", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = id;
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = pw;
da.SelectCommand = cmd;
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
iD = (dr["#ID"].ToString());
password = dr["#PASSWORD"].ToString();
}
if (iD == id && password == pw)
{
return true;
}
else
{
LogNotification = "ID/Password is incorrect";
return false;
}
}
I am getting sql errors at getting the login to work, how do I get the ds to work to allow me to connect to the database and login?
The error says ds is not right, and the sql server exception was not caught
Student:
class Student : Person
{
private String iD;
private String password;
private String eMail;
private double gpa;
private String message;
public Student() : base()
{
this.iD = "";
this.password = "";
this.eMail = "";
this.gpa = 0;
}
public Student(String i, String pa, String eM, int gp) : base()
{
this.iD = i;
this.password = pa;
this.eMail = eM;
this.gpa = gp;
InsertDB();
}
public Student(String 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(String 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(String 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 String 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 string LogNotification { get; set; }
public bool ConfirmLogin(string id, string pw)
{
using (SqlConnection con = new SqlConnection("Data Source=c:\\RegistrationMDB.accdb"))
{
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT ID, PASSWORD FROM Students WHERE ID = #ID OR PASSWORD = #PASSWORD", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = id;
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = pw;
da.SelectCommand = cmd;
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
iD = (dr["#ID"].ToString());
password = dr["#PASSWORD"].ToString();
}
if (iD == id && password == pw)
{
return true;
}
else
{
LogNotification = "ID/Password is incorrect";
return false;
}
}
}
public void displays(){
System.Console.WriteLine("ID = "+ getID());
System.Console.WriteLine("Password = "+ getPassword());
System.Console.WriteLine("Email = " + getEMail());
System.Console.WriteLine("GPA = " + getGpa());
}
}
StudentLogin form:
namespace Students
{
public partial class StudentLogin : Form
{
public StudentLogin()
{
InitializeComponent();
}
private void Logingo_Click(object sender, EventArgs e)
{
Student st = new Student();
if(st.ConfirmLogin(textBox1.Text,textBox2.Text)==false){
MessageBox.Show(st.LogNotification);
}
else{}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
It does not catch the SQLException from the try catch. To print the exception use SQLException in your catch.
The error:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections.
appears when your application cannot communicate with the database. It's probably your ConnectionString that you should take a look at.

"Table already exists" but it doesn't

I'm getting an This Table already exists error from Visual Studio 2012. I checked it in MySqlWorkbench and the Xampp Directory, but I didn't find anything. I've even tried it with DROP TABLE IF EXISTS tablename; but this doesn't work either.
public class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "";
uid = "root";
password = "";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
connection.Dispose();
CreateDatabase(" DROP DATABASE IF EXISTS boerswatch; CREATE DATABASE boerswatch;");
server = "localhost";
database = "boerswatch";
uid = "root";
password = "";
string connectionString1;
connectionString1 = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString1);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException e)
{
switch (e.Number)
{
case 0:
MessageBox.Show("Keine Verbindung zum Server Möglich!");
break;
case 1045:
MessageBox.Show("Ungültiger Benutzername oder Passwort!");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException e)
{
MessageBox.Show(e.Message);
return false;
}
}
public void CreateDatabase(String query)
{
if (OpenConnection())
{
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
CloseConnection();
}
catch (MySqlException e)
{
MessageBox.Show(e.Message);
}
}
}
public void CreateTable(String query)
{
if (OpenConnection())
{
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
CloseConnection();
}
catch (MySqlException e)
{
MessageBox.Show(e.Message);
}
}
}
public void Insert(String query)
{
if (this.OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
}
public partial class Form1 : Form
{
static XmlSerializer serializer;
static FileStream stream;
public List<Bank> banks;
public List<Object> pers;
public DBConnect data;
public Form1()
{
InitializeComponent();
checkFiles();
}
private void checkFiles()
{
String user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
banks = new List<Bank>(5);
if (!Directory.Exists(#"C:\xampp\mysql\data\boerswatch") )
{
data = new DBConnect();
createBanks();
}
else
{
//loadBanks();
//loadAccounts(pers);
}
}
public void createBanks()
{
Bank b1 = new Bank("Raiffeisen");
Bank b2 = new Bank("Erste Bank");
Bank b3 = new Bank("BAWAG");
banks.Add(b1);
banks.Add(b2);
banks.Add(b3);
data.CreateTable("DROP TABLE IF EXISTS Banken; CREATE TABLE Banken( name VARCHAR(20) PRIMARY KEY);");
data.Insert("INSERT INTO Banken VALUES(" + b1.Name + ");");
data.Insert("INSERT INTO Banken VALUES(" + b2.Name + ");");
data.Insert("INSERT INTO Banken VALUES(" + b3.Name + ");");
listBox1.DataSource = banks;
}
}

Categories