The database is laid out as such:
Table: VISITOR
Fields: ID (Primary key int autoincrement), and NAME (string)
Table: ATTENDANCE
Fields: VISITID (int autoincrement) VISITORID (ID from VISITOR table), and DATE (current date)
I feel I am doing things very wrong and also want to add in a check to see if the database exists and if not then create it. This is called from a simple WPF window which has one text box and one button on it. I know I don't really have it sanitize my input because I am unsure how and this was made using Google and lots of trial and error. I also have never worked with a database up until now so I am learning that at the same time and am looking for constructive feedback on my code if possible.
Thank you
using System;
using System.Data;
using System.Data.SqlServerCe;
using System.Xml;
namespace client
{
internal class DbEngine
{
internal void CheckVisitor(string VisitorName)
{
int NameMatches;
SqlCeConnection DbConnection = new SqlCeConnection(@"Data Source=.\members.sdf;Persist Security Info=False;");
using (DbConnection)
{
if (DbConnection.State != ConnectionState.Open)
{
DbConnection.Open();
}
SqlCeCommand SearchCommand = new SqlCeCommand("select * from VISITORS where NAME = (@VisitorName)", DbConnection);
SearchCommand.Parameters.AddWithValue("@VisitorName", VisitorName);
SqlCeDataAdapter adapter = new SqlCeDataAdapter();
using (adapter)
{
adapter.SelectCommand = SearchCommand;
DataTable dt = new DataTable();
adapter.Fill(dt);
NameMatches = dt.Rows.Count;
if (NameMatches == 1)
{
AddVisitorDate(int.Parse(dt.Rows[0]["ID"].ToString()));
}
else
{
AddVisitor(VisitorName);
CheckVisitor(VisitorName);
}
}
}
}
internal void AddVisitor(string VisitorName)
{
SqlCeConnection DbConnection = new SqlCeConnection(@"Data Source=.\members.sdf;Persist Security Info=False;");
using (DbConnection)
{
DbConnection.Open();
SqlCeCommand SqlCeInsertComm = new SqlCeCommand("insert into VISITORS (NAME) VALUES (@VisitorName)", DbConnection);
using (SqlCeInsertComm)
{
SqlCeInsertComm.Parameters.AddWithValue("@VisitorName", VisitorName);
SqlCeInsertComm.ExecuteNonQuery();
}
}
}
internal void AddVisitorDate(int VisitorID)
{
SqlCeConnection DbConnection = new SqlCeConnection(@"Data Source=.\members.sdf;Persist Security Info=False;");
using (DbConnection)
{
DbConnection.Open();
SqlCeCommand SqlCeInsertComm = new SqlCeCommand("insert into ATTENDANCE (VISITOR, DATE) VALUES (@VisitorId, @VisitDate)", DbConnection);
using (SqlCeInsertComm)
{
SqlCeInsertComm.Parameters.AddWithValue("@VisitorId", VisitorID);
SqlCeInsertComm.Parameters.AddWithValue("@VisitDate", DateTime.Now.ToShortDateString());
SqlCeInsertComm.ExecuteNonQuery();
}
}
}
}
}

New Topic/Question
Reply




MultiQuote




|