If in php we can do something like where $result is some query:
$result = mysql_query("SELECT * FROM student");
if (mysql_num_rows($results) !==0)
{
//do operation.
}
else
echo "no data found in databasae";
What is equivalent to this if I want to do this in C# language?please advise.
I have Created a full Console application using mysql. In your select query you are querying the whole table which is a bad idea. use limit to get only one result - this should be enough to determine if there are any rows in the table.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql;
using MySql.Data.MySqlClient;
namespace ConsoleApplication29
{
class Program
{
static void Main(string[] args)
{
if (AnyRows())
{
Console.WriteLine("There are rows in the database");
}
else
Console.WriteLine("no data found in database");
//This will pause the output so you can view the results. Otherwise you will see the dos screen open then close.
Console.Read();
}
//This is the Methos to call
public static bool AnyRows()
{
string connectionString = "Server=localhost;Database=test;Uid=root;Pwd=yourpassword;";
//Wrap this is using clause so you don't have to call connection close
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "select * from mytable limit 1";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
MySqlDataReader reader = command.ExecuteReader();
return reader.HasRows;
}
}
}
}
}
assuming "results" is of type int
if(results != 0)
{
//do operation
}
else
{
Console.WriteLine("..."); //or output elsewhere
}
c# if else
add a reference to linq, and it gets really easy
var result = SomeDatabaseCall();
if (result.Any()){
// do something
}
if you want to filter the results even further, you can do that inside the Any
var result = SomeDatabaseCall();
if (result.Any(r => r.ID == SomeID)){ // ID can be replaced with any properties in your return model
// do something
}
I got the solution. It is actually very simple. BTW thanks for those who helping. This is the solution:
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public DBConnect()
{
Initialize();
}
private void Initialize()
{
server = "your_server";
database = "your_db";
uid = "usr";
password = "pwd";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void Select()
{
string query = "SELECT * FROM table";
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data in the database
if (dataReader.HasRows == true)
{
while (dataReader.Read())
{
//do retrieve data
}
}else
{
MessageBox.Show("There's no recods in the database");
}
}
}
}
It's best to use SELECT 1 instead of grabbing unnecessary data from the database to simply check for the existence of rows.
public static bool IsTableEmpty(string tableName)
{
string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
using (var conn = new MySqlConnection(cs))
{
conn.Open();
string sql = string.Format("SELECT 1 FROM {0}", tableName);
using (var cmd = new MySqlCommand(sql, conn))
{
using (var reader = cmd.ExecuteReader())
{
return !reader.HasRows;
}
}
}
}
If you want to get the row count, then you'll need something like:
public static int GetTableRowCount(string tableName)
{
string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
using (var conn = new MySqlConnection(cs))
{
conn.Open();
string sql = string.Format("SELECT COUNT(*) FROM {0}", tableName);
using (var cmd = new MySqlCommand(sql, conn))
{
return Convert.ToInt32(cmd.ExecuteScalar());
}
}
}
Related
I want to create a database if it does not exist. I am trying to do it with this code but it has errors and I get this message
enter image description here
Please help.
Code:
if(dbex == false)
{
string str;
SqlConnection mycon = new SqlConnection("Server=.\\sqlexpress;initial catalog=Masalehforoshi;Integrated security=SSPI;database=master");
str = "CREATE DATABASE [Masalehforoshi] CONTAINMENT = NONE ON PRIMARY" +
"(NAME=N'Masalehforoshi'," +
#"FILENAME=N'C:\data\Masalehforoshi.mdf' " +
",SIZE=3072KB,MAXSIZE=UNLIMITED,FILEGROWTH=1024KB)" +
"LOG ON (NAME=N'Masalehforoshi_log.', " +
#"FILENAME=N'C:\Masalehforoshi_log.ldf' "+
",SIZE=1024KB,MAXSIZE=2048GB,FILEGROWTH=10%)";
SqlCommand mycommand = new SqlCommand(str, mycon);
try
{
mycommand.Connection.Open();
mycommand.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(), "myprogram", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
finally
{
if(mycon.State == ConnectionState.Open)
{
mycon.Close();
}
}
}
My Create Database function
public bool CreateDatabase(SqlConnection connection, string txtDatabase)
{
String CreateDatabase;
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
GrantAccess(appPath); //Need to assign the permission for current application to allow create database on server (if you are in domain).
bool IsExits = CheckDatabaseExists(connection, txtDatabase); //Check database exists in sql server.
if (!IsExits)
{
CreateDatabase = "CREATE DATABASE " + txtDatabase + " ; ";
SqlCommand command = new SqlCommand(CreateDatabase, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show("Please Check Server and Database name.Server and Database name are incorrect .", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
return true;
}
return false;
}
My GrantAccess function to allow permission for current app
public static bool GrantAccess(string fullPath)
{
DirectoryInfo info = new DirectoryInfo(fullPath);
WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();
DirectorySecurity ds = info.GetAccessControl();
ds.AddAccessRule(new FileSystemAccessRule(self.Name,
FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit |
InheritanceFlags.ContainerInherit,
PropagationFlags.None,
AccessControlType.Allow));
info.SetAccessControl(ds);
return true;
}
Check Database exists function below
public static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName)
{
string sqlCreateDBQuery;
bool result = false;
try
{
sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName);
using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
{
tmpConn.Open();
object resultObj = sqlCmd.ExecuteScalar();
int databaseID = 0;
if (resultObj != null)
{
int.TryParse(resultObj.ToString(), out databaseID);
}
tmpConn.Close();
result = (databaseID > 0);
}
}
catch (Exception)
{
result = false;
}
return result;
}
Based on this support article https://support.microsoft.com/en-us/kb/307283 which has a similar database creation script I suggest removing the "CONTAINMENT = NONE" section.
By default, all SQL Server 2012 and later databases have a containment set to NONE.(https://msdn.microsoft.com/en-us/library/ff929071.aspx), so it probably isn't necessary for your script
It is possible that ado .net doesn't support that tsql command, there is a whole other SQL Server Management Objects library available for messing with advance database and schema scripts https://msdn.microsoft.com/en-us/library/ms162169.aspx . I've used it to create missing databases with table definitions etc during application startup.
To simplify things, here is an even shorter solution.
public void CreateDatabaseIfNotExists(string connectionString, string dbName)
{
SqlCommand cmd = null;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (cmd = new SqlCommand($"If(db_id(N'{dbName}') IS NULL) CREATE DATABASE [{dbName}]", connection))
{
cmd.ExecuteNonQuery();
}
}
}
Yo this is my first post here and i wanna know how to fix this problem in C#
so im tryin to connect to database and select information from it and those information will be displayed as a label ! easy,
so this is the error i get :
cannot access a non-static member of outer type 'windowsForm8.Form1'
via nested Type 'windowsForm8.Form1.DBConnect'
and this is the Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
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 = "net";
database = "rainbow";
uid = "ok";
password = "passwd!";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
default :
MessageBox.Show("Connected Successfuly!!");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO mytable (username, password) VALUES('shryder', 'nopassword')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update()
{
}
//Delete statement
public void Delete()
{
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM mytable";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
if (dataReader.Read())
{
/*list[0].Add(dataReader["username"] + "");
list[1].Add(dataReader["password"] + "");
list[2].Add(dataReader["email"] + "");*/
newscontent.Text = dataReader["username"]; //this is the error
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}
}
}
please help me
,thanks :)
Move all your code from the class DbConnect yo your Form1 class. Then all of your methods have access to your form controls.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Initialize values
private void Initialize()
{
server = "net";
database = "rainbow";
uid = "ok";
password = "passwd!";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
default :
MessageBox.Show("Connected Successfuly!!");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO mytable (username, password) VALUES('shryder', 'nopassword')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update()
{
}
//Delete statement
public void Delete()
{
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM mytable";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
if (dataReader.Read())
{
/*list[0].Add(dataReader["username"] + "");
list[1].Add(dataReader["password"] + "");
list[2].Add(dataReader["email"] + "");*/
newscontent.Text = dataReader["username"]; //this is the error
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
//Backup
public void Backup()
{
}
//Restore
public void Restore()
{
}
}
}
}
Like this your code ahould be able to access the labels, so it should compile. It still doesn't do anything since none of the methods are called.
Edited this on my phone, so couldn't test the code.
Before anyone votes my question down, I would like to say that this is my first time using classes in C# and I have done a lot of research but I am still encountering errors. Newbie here.
I am trying to put the Insert, Delete, Update, and Count statements in a class file so that my code will be neat.
Here is the class file I made (with the help of research of course):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.IO;
using System.Windows.Forms;
namespace classlib
{
public class DBConnect
{
private static MySqlConnection mycon;
private string server;
private string database;
private string uid;
private string password;
public DBConnect()
{
Initialize();
}
private void Initialize()
{
server = "localhost";
database = "restaurantdb";
uid = "user";
password = "root";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
mycon = new MySqlConnection(connectionString);
}
private static bool OpenConnection()
{
try
{
mycon.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
private static bool CloseConnnection()
{
try
{
mycon.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public static void Insert(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static void Update(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = mycon;
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static void Delete(string query)
{
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
cmd.ExecuteNonQuery();
CloseConnnection();
}
}
public static int Count(string query)
{
int count = -1;
if (OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, mycon);
count = int.Parse(cmd.ExecuteScalar() + "");
CloseConnnection();
return count;
}
else
{
return count;
}
}
}
}
I was just trying the Count Method like in a certain form. Here is my code:
MessageBox.Show("NUMBER OF ACCOUNTS IN DATABASE = "+ DBConnect.Count("SELECT count(*) FROM usersettingsdb") +"", "CONFIRMATION");
But I get this error on the class file on the OpenConnection() method on the mycon.Open() line:
Object reference not set to an instance of an object.
How do I remove the said error and access the methods through calling it like so DBConnect.MethodName()?
I don't quite get anything about classes but I would really like to know how I can create my own functions/methods so as to keep my code neat.
Ok this is because you are messing up thing using in some cases static fields and in other cases not. There are tons of paper about static classes/members, see here for example.
The initialization code won't be called if you use the class as you are using.
In your case you should have a DBConnect instance and remove the static from methods
var db = new DBConnect();
and then use that in order to make queries:
db.Count(...);
Another solution is to call the Initialize method inside the Count method. You should modify Initialize in order to make it static (you will have to make all of your fields as static)
Another users will answer this question propably. So I want to mention different things. Your code is not very good. Instead of using it ,you can take a look at use of repository pattern. You can also use petapoco for database. These facilitate your work.
http://www.remondo.net/repository-pattern-example-csharp/
http://www.toptensoftware.com/petapoco/
Your myCon object is initialized in the Initialize() method, which is called in the constructor of the class, so only when you create an instance of DbConnect.
mycon = new MySqlConnection(connectionString);
In your code, you have no instance of DbConnect, you just call the static method Count of the class. So, the myCon is null.
I'm trying to do something like this:
public void ImportClick(object sender, EventArgs e) //the button used after selecting the spreadsheet file
{
if (fileUpload.HasFile) //ASP.Net FileUpload control
{
if (fileUpload.FileName.EndsWith(".xls", StringComparison.OrdinalIgnoreCase) || fileUpload.FileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase))
{
Excel sheet = new Excel(fileUpload.Open()); //not sure how to do this part
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["our_database"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("INSERT INTO table_name SELECT * FROM " + sheet, connection))
{
connection.Open();
command.ExecuteQuery(); //Intellisense only has "ExecuteNonQuery()" method, but that's for T-SQL
connection.Close();
}
}
}
else
{
error.Text = "File must be either *.xls or *.xlsx";
error.Visible = true;
}
}
else
{
error.Text = "No file was selected";
error.Visible = true;
}
}
There are a lot of classes and interfaces in the Microsoft.Office.Interop.Excel namespace, and I don't know which one to use.
I know making the Excel object, along with the SQL command, probably won't be as easy as what I have here, but those are the two things I need help with.
Any suggestions/advice would be greatly appreciated!
I would suggest using Microsoft Jet Engine.
private static void UploadExcelToDB(string p)
{
try
{
using (SqlConnection conn = new SqlConnection(DBConnString))
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
Log("Opened connection to DB");
}
SqlBulkCopy sbk = new SqlBulkCopy(conn);
sbk.BulkCopyTimeout = 600;
sbk.DestinationTableName = DbTableName;
DataTable excelDT = new DataTable();
OleDbConnection excelConn = new OleDbConnection(ExcelConnString.Replace("xFILEx",p));
excelConn.Open();
if (excelConn.State == ConnectionState.Open)
{
Log("Opened connection to Excel");
}
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
cmdExcel.CommandText = "SELECT * FROM ["+ExcelTableName+"]";
cmdExcel.Connection = excelConn;
oda.SelectCommand = cmdExcel;
oda.Fill(excelDT);
if (excelDT != null)
{
Log("Fetched records to local Data Table");
}
excelConn.Close();
SqlCommand sqlCmd = new SqlCommand("TRUNCATE TABLE ICN_NUGGET_REPORT_RAW",conn);
sqlCmd.CommandType = CommandType.Text;
Log("Trying to clear current data in table");
int i = sqlCmd.ExecuteNonQuery();
Log("Table flushed");
Log("Trying write new data to server");
sbk.WriteToServer(excelDT);
Log("Written to server");
conn.Close();
}
}
catch (Exception ex)
{
Log("ERROR: " + ex.Message);
SendErrorReportMail();
}
finally
{
#if (DEBUG)
{
}
#else
{
string archive_file = ArchiveDir+"\\" + DateTime.Now.ToString("yyyyMMdd-Hmmss") + ".xlsx";
File.Move(p, archive_file);
Log("Moved processed file to archive dir");
Log("Starting archive process...");
}
#endif
}
}
This is how ExcelConnString looks like:
public static string ExcelConnString { get { return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=xFILEx;Extended Properties=\"Excel 12.0;HDR=YES\";";} }
HDR=YES - this means that if you have column names in spreadsheet it will be treated as target table column names for matching each other.
I am thinking of creating an instance of excel.application class and writing codes to loop through the cells. And using SQL insert query to copy the rows one by one to the SQL table. I'm still working it out anyway and would paste the code when i'm done.
I am working on part of my program where I am deleting entry by using provided Entry ID.
As of right now I am deleting any entry specified by user. This works great but, what I am trying to do is to inform user that there is no such ID to delete. Also, I am using textbox TextChanged which let me to check for certain things in user input while user is typing.
Now, how do I check if Entry ID already exists? What should I include in my if statement to do this?
Also, is there a way I could check that by using TextChanged event handler? I'm not sure about that because I know that if I would have opening and closing connection in TextChanged event, then connection would be opened/closed every time user is typing, so I don't think this is a good idea. But how can I avoid this and so I can do this in real time? Perhaps when user stop typing, and then take a second or two to check for entry id?
This is a code of my delete entry window:
public partial class DeleteEntryWindow : Form
{
string user, pass, filePath;
// Initializing MainWindow form.
MainWindow mainWindow;
public DeleteEntryWindow()
{
InitializeComponent();
txtEntryID.TextChanged += new EventHandler(ValidateInput);
}
public DeleteEntryWindow(MainWindow viaParameter,
string user, string pass, string filePath)
: this()
{
mainWindow = viaParameter;
this.user = user;
this.pass = pass;
this.filePath = filePath;
}
private void ValidateInput(object sender, EventArgs e)
{
int intNumber;
if (!string.IsNullOrEmpty(txtEntryID.Text) &&
int.TryParse(txtEntryID.Text, out intNumber) &&
intNumber > 0)
{
lblMessage.Text = "Entry ID is valid.";
lblMessage.ForeColor = Color.Green;
btnDeleteEntry.Enabled = true;
}
else
{
lblMessage.Text = "You must enter Entry ID number!";
lblMessage.ForeColor = Color.IndianRed;
btnDeleteEntry.Enabled = false;
}
}
private void btnDeleteEntry_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show
("Are you sure you want to remove this entry?",
"Information", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
// SQL query which will delete entry by using entry ID.
string sql = "DELETE FROM PersonalData WHERE DataID = " +
txtEntryID.Text;
DeleteData(sql);
lblMessage.Text = "Entry was deleted!";
lblMessage.ForeColor = Color.Green;
}
else
{
// Do nothing.
}
}
private void DeleteData(string sql)
{
HashPhrase hash = new HashPhrase();
string hashShortPass = hash.ShortHash(pass);
// Creating a connection string. Using placeholders make code
// easier to understand.
string connectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};
Persist Security Info=False; Jet OLEDB:Database Password={1};";
using (OleDbConnection connection = new OleDbConnection())
{
// Creating command object.
// Using a string formatting let me to insert data into
// place holders I have used earlier.
connection.ConnectionString =
string.Format(connectionString, filePath, hashShortPass);
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
OleDbParameter prmDataID = new OleDbParameter
("#DataID", txtEntryID.Text);
command.Parameters.Add(prmDataID);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
}
To check if the ID already exists, you will need to use SQL just as your delete method does. The following may give you a starting point:
private bool DoesIDExist(string ID)
{
string filePath = ""; //TODO
string hashShortPass = ""; //TODO
DataTable temp = new DataTable();
bool result = false;
string connectionString =""; //TODO
using (OleDbConnection connection = new OleDbConnection(ConnectionString))
{
string sql = #"SELECT * FROM PersonalData WHERE DataID = #DataID";
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
command.Parameters.Add(new OleDbParameter("#DataID", ID));
using (OleDbDataAdapter oda = new OleDbDataAdapter(command))
{
try
{
oda.Fill(temp);
if (temp != null && temp.Rows.Count > 0)
result = true; //ID exists
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
return result;
}