"Table already exists" but it doesn't - c#

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;
}
}

Related

C# SQL Connection string " can't find the table "

Currently I'm working on a project that generates files....().
Everything seems to work well. I can connect to the database and my methods of reading and writing are working, too, but I can't find the table. I have an error:
$exception {"Invalid object name 'T_SAL'."} System.Data.SqlClient.SqlException
I don't know if the problem is with my connection string or something else!
Is there anyone that can help me with this, please?
My methods' code:
//SQL connection Methods**
public static SqlConnection OpenSql(bool Authentification, string SQL_LOGIN, string SQL_PASSWORD, string SQL_SERVER, string BASE_CONSOLE)
{
try
{
SqlConnection conn = new SqlConnection();
String Securité;
if (Authentification)
{
Securité = "Integrated Security = true";
}
else
{Securité = "User Id =" + SQL_LOGIN + ";" + "Password =" + SQL_PASSWORD;}
conn.ConnectionString = "Data Source=" + SQL_SERVER + ";Initial Catalog=" + BASE_CONSOLE + ";" + Securité + ";";
conn.Open();
return conn;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return null;
}
// Generation :
private void Gen_f_Click(object sender, EventArgs e)
{
SqlConnection conn = Methodes.OpenSql(Authentification.Checked, SQL_SERVER.Text, BASE_CONSOLE.Text, SQL_LOGIN.Text, SQL_PASSWORD.Text );
if (conn == null)
{
MessageBox.Show("Connexion impossible");
return;
}
try
{
//traitement du fichier des salaeiés
var lines = Methodes.lecture(fp_text.Text);
foreach (var ligne in lines)
{
string[] cols = ligne.Split(char.Parse(";"));
string Matricule = cols[0];
if (Matricule != "" && MatriculeExiste(conn, Matricule) == false)
{
string ligneSorties = "";
ligneSorties = ligneSorties + cols[0] + ";";
Methodes.Ecriture(ligneSorties, "fp_sorties.'Text'", true);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private bool MatriculeExiste(SqlConnection conn, string Matricule)
{
SqlCommand command = new SqlCommand("SELECT MatriculeSalarie FROM [T_SAL] WHERE MatriculeSalarie='" + Matricule + "'", conn);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
return true;
}
else
{
return false;
}
}
}
The issue seems to be in the order of parameters that you pass to OpenSql method:
public static SqlConnection OpenSql(bool Authentification, string SQL_LOGIN, string SQL_PASSWORD, string SQL_SERVER, string BASE_CONSOLE)
This is how you call it:
SqlConnection conn = Methodes.OpenSql(Authentification.Checked, SQL_SERVER.Text, BASE_CONSOLE.Text, SQL_LOGIN.Text, SQL_PASSWORD.Text );
There is definitely some mismatch with the order of parameters, your declaration expects SQL_Login, SQL_PASSWORD, SQL_SERVER, BASE_CONSOLE and you are passing SQL_SERVER, BASE_CONSOLE, SQL_LOGIN, SQL_PASSWORD
So if you use Windows Authentication, it would work, because you are not passing login and password, but instead of correct Database Name you are passing password, so your user ends up into Master db, which does not contain required table.

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 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.

three tier database in C#

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;
}
}

Verify if mysql command executed

I am using
public static bool command(string input, MySqlConnection con)
{
MySqlCommand command = new MySqlCommand(input, con);
var resultSet = command.ExecuteNonQuery();
if (!resultSet.Equals(0))
return true;
return false;
}
With as an example:
bool comm = mysql_command.command("INSERT INTO sometable (field1,field2) VALUES ('val1','val2')", connection);
if (!comm) textBox1.Text += "Command failed";
else textBox1.Text += "Command successful";
Which correctly adds Command successful to textbox1.
But when I change sometable to sometablee, textbox1 stays empty. I was expecting it to notify me the command failed (sometablee does not exist), but it didn't.
Can anyone tell me why?
Full code:
mysql_command:
class mysql_command
{
public static bool command(string input, MySqlConnection con)
{
MySqlCommand command = new MySqlCommand(input, con);
var resultSet = command.ExecuteNonQuery();
if (!resultSet.Equals(0))
return true;
return false;
}
}
mysql_connect:
class mysql_connect
{
private MySqlConnection connection = null;
public MySqlConnection connect(string server, string database, string UID, string password)
{
try
{
string MyConString = "SERVER=" + server + ";" +
"DATABASE=" + database + ";" +
"UID=" + UID + ";" +
"PASSWORD=" + password + ";";
connection = new MySqlConnection(MyConString);
connection.Open();
}
catch (Exception ex) { Console.WriteLine("MySQL connect error : "+ex.Message); }
return connection;
}
public void disconnect()
{
connection.Close();
}
}
Usage:
private void Form1_Load(object sender, EventArgs e)
{
mysql_connect con = new mysql_connect();
MySqlConnection connection = con.connect("server1.x.x", "somedb", "user", "pass");
bool comm = mysql_command.command("INSERT INTO sometable (field1,field2) VALUES ('val1','val1')", connection);
if (!comm) textBox1.Text += "Command failed";
else textBox1.Text += "Command successful";
}
The reason is as I expected, you will get an exception in your command method,
public static bool command(string input, MySqlConnection con)
because requested table is not exists, ....
Edit your command method to handle exception:
public static bool command(string input, MySqlConnection con)
{
try
{
MySqlCommand command = new MySqlCommand(input, con);
var resultSet = command.ExecuteNonQuery();
if (!resultSet.Equals(0))
return true;
return false;
}
catch
{}
return false;
}

Categories