Always use parameters. This allows one to safely inject the right data.
public int AddUser(Logic.Employee details)
{
int lastId = 0;
string MyConString = "server=localhost;database=crawler_attendance;Username=root;Password=crawl;";
MySqlConnection conn = new MySqlConnection(MyConString);
try
{
string dbQuery = string.Empty;
dbQuery = String.Format(@"INSERT INTO employeeTEST(username,firstname,lastname,company)
VALUES(@username,@firstname,@lastname,@company)");
MySqlCommand cmd = new MySqlCommand(dbQuery, conn);
cmd.Parameters.AddWithValue("@username", details.userName);
cmd.Parameters.AddWithValue("@firstname", details.firstName);
cmd.Parameters.AddWithValue("@lastname", details.lastName);
cmd.Parameters.AddWithValue("@company", details.company);
conn.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Add(new MySqlParameter("lastId", cmd.LastInsertedId));
lastId = Convert.ToInt32(cmd.Parameters["@lastId"].Value);
}
catch (Exception e)
{
conn.Close();
}
finally
{
conn.Close();
}
return lastId;
}
public int AddUser(Logic.Employee details)
{
int lastId = 0;
string MyConString = "server=localhost;database=crawler_attendance;Username=root;Password=crawl;";
MySqlConnection conn = new MySqlConnection(MyConString);
try
{
string dbQuery = string.Empty;
dbQuery = String.Format(@"INSERT INTO employeeTEST(username,firstname,lastname,company)
VALUES(@username,@firstname,@lastname,@company)");
MySqlCommand cmd = new MySqlCommand(dbQuery, conn);
cmd.Parameters.AddWithValue("@username", details.userName);
cmd.Parameters.AddWithValue("@firstname", details.firstName);
cmd.Parameters.AddWithValue("@lastname", details.lastName);
cmd.Parameters.AddWithValue("@company", details.company);
conn.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Add(new MySqlParameter("lastId", cmd.LastInsertedId));
lastId = Convert.ToInt32(cmd.Parameters["@lastId"].Value);
}
catch (Exception e)
{
conn.Close();
}
finally
{
conn.Close();
}
return lastId;
}
No comments:
Post a Comment