There is no error in the code but no data is inserted in the database
follwing is the code of each layer
User Layer :
private void btnSave_Click(object sender, EventArgs e)
{
EmpProps p = new EmpProps();
p.Code1 = Convert.ToInt32(tfId.Text);
p.Name1 = tfName.Text;
p.Cell1 = tfCell.Text;
p.Adrs1 = tfAdrs.Text;
p.Dept1 = cmbDept.Text;
EmpBll eb = new EmpBll();
bool b =eb.InsertEmpBll(p);
if(b)
{ MessageBox.Show("Saved successfully");
}
else
{ MessageBox.Show("Error Ocurred");
}
}
Logic Layer :
public class EmpBll
{
public bool InsertEmpBll(EmpProps p)
{
EmpDal empdal = new EmpDal();
bool b =empdal.InsrtEmpDal(p);
if (b)
return true;
else
return false;
}
}
Data Access layer :
public class EmpDal
{
public bool InsrtEmpDal(EmpProps p)
{
SqlConnection conn = new SqlConnection("Data Source=DASTGIRKHAN\\SQLEXPRESS;Initial Catalog=MultilayerManagementSystem;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand("Insert INTO EmployeeRecord Values(" + p.Code1.GetType() + ",'" +p.Name1 + "','" + p.Cell1 + "','" +p.Adrs1 + "','" + p.Dept1 + "')", conn);
conn.Open();
int c= cmd.ExecuteNonQuery();
conn.Close();
if (c > 0)
return true;
else
return false;
}
}
Related
How to Display the User Id in my Homepage in ASP MVC. I don't know what is the problem. May I know what are the cause the userId
This is the part of Dashboard
protected void Page_Load(object sender, EventArgs e)
{
string sUserInfo = System.Environment.UserName;
string constr = "Data Source=MyDatabase;Database=test;User Id=username;Password=add3" ;
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("Select SystemName from tbl_SYS_Users where UserId='" + sUserInfo + "'");
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
string tempa = "";
while (sdr.Read())
{
tempa += sdr["SystemName"].ToString();
}
lblUserID.Text = Utilities.GetUserInfo(tempa);
}
This is for the Utilities in AppData Folder
public static string GetUserInfo(string sSystem)
{
sSystem = sSystem.ToUpper();
string sUserInfo = System.Environment.UserName;
if (SetConfigs()) //Check config file first
{
//Get userinfo from db server
if (sSystem != "HOME")
{
string sQry = "Select * from tbl_SYS_Users where SystemName = '" + sSystem + "' AND UserId='" + sUserInfo + "'";
using (DataTable dsTable = SQL_Query(Globals.sSQLCS_FNS, sQry, true, false))
{
if (dsTable == null)
{
sUserInfo += " - Unknown User!a";
Globals.UserID = null;
Globals.UserAccess = "";
Globals.UserName = null;
}
else
{
if (dsTable.Rows.Count == 0) //ID not found!
{
sUserInfo += " - Unknown User!";
Globals.UserID = null;
Globals.UserAccess = "";
Globals.UserName = null;
}
else
{
sUserInfo += " - " + dsTable.Rows[0]["Username"];
Globals.UserID = dsTable.Rows[0]["UserId"].ToString().Trim();
Globals.UserName = dsTable.Rows[0]["Username"].ToString().Trim();
}
}
}
}
}
else if (sSystem != "HOME")
sUserInfo += " - Unknown User!s";
return sUserInfo; // return to lblUserID.Text in the homepage
}
This image is the homepage
This is the database
I Want to display the Username in my Homepage
inject usermanager in to the view and add this
#UserManager.GetUserAsync(User).Result.UserName
What is the scope of Globals class? It seems when page loads class object initialized and all becomes empty. Declare Globals class as static (If not).
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);
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.
I want to get next record from table to show as Question. With below code I am not able to get next Question from table.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
Quiz_Load();
}
}
private void Quiz_Load()
{
try
{
if (Session["UserQuizID"] != null)
{
string mayank = "mm.bhagat";
string UserQuiz_ID = Session["UserQuizID"].ToString();
SqlConnection con = new SqlConnection(c);
SqlCommand cmd = new SqlCommand("select top 0.1 percent QuestionID, Title, Answer1,Answer2,Answer3,Answer4,UserAnswer from [Table_UserAnswer] WHERE UserQuizID = '" + UserQuiz_ID.ToString() + "' AND UserName = '" + mayank.ToString() + "' order by newid()", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Session["QuestionID"] = dr[0].ToString();
Lbl_QuestionTitle.Text = dr[1].ToString();
RadBut_Answer.Items.Add(dr[2].ToString());
RadBut_Answer.Items.Add(dr[3].ToString());
RadBut_Answer.Items.Add(dr[4].ToString());
RadBut_Answer.Items.Add(dr[5].ToString());
Session["UserAnswer"] = dr[6].ToString();
}
else
{
}
con.Close();
}
else
{
Response.Redirect("Start.aspx");
}
}
catch
{
}
}
protected void RadBut_Answer_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int getvalue;
getvalue = Convert.ToInt32(RadBut_Answer.SelectedIndex + 1);
Lbl_SelectedAnsMsg.Text = MessageFormatter.GetFormattedAlertsMessage("Your Selected Answer is : " + getvalue.ToString());
Session["UserAnswer"] = getvalue.ToString();
}
catch
{
}
}
protected void But_Next_Click(object sender, EventArgs e)
{
UpdateUserAns();
if (Session["UserAnswer"] == null)
{
Response.Redirect("Result.aspx");
}
else
{
}
}
private void UpdateUserAns()
{
try
{
string mayank = "mm.bhagat";
string UserQuiz_ID = Session["UserQuizID"].ToString();
string Question_ID = Session["QuestionID"].ToString();
string User_Answer = Session["UserAnswer"].ToString();
SqlConnection con = new SqlConnection(c);
SqlCommand cmd = new SqlCommand("UPDATE Table_UserAnswer SET UserAnswer='" + User_Answer.ToString() + "' WHERE UserQuizID = '"+ UserQuiz_ID.ToString() +"' AND QuestionID = '"+Question_ID.ToString()+"' AND UserName = '"+mayank.ToString()+"'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Cancel();
}
catch
{
}
}
hi check this post client here
here you can find solution of your question
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;
}
}