textBox to DateTime in DB - c#

Iam trying to get a DateTime out of an textBox, where it allready is in Format of MySql DateTime. The column in the DB is also DateTime format.
However, when i press my button to save the Dates in the DB, the whole row is gonna get emptyed.
I tried around with different formats und DataTypes in DB without anny effect
private void button4_Click(object sender, EventArgs e)
{
MySqlConnection conn = DBUtils.GetDBConnection();
conn.Open();
string startzeit = textBoxstartzeit.Text.ToString();
DateTime start = DateTime.Parse(startzeit);
string stopzeit = textBoxstopzeit.Text.ToString();
DateTime stop = DateTime.Parse(stopzeit);
string pstartzeit = textBoxstopzeit.Text.ToString();
DateTime pstart = DateTime.Parse(pstartzeit);
string pstopzeit = textBoxstopzeit.Text.ToString();
DateTime pstop = DateTime.Parse(pstopzeit);
MySqlCommand cmdnew = conn.CreateCommand();
cmdnew.CommandType = CommandType.Text;
cmdnew.CommandText = "UPDATE arbeitszeiten SET astart = '" + start + "', astop = '" + stop + "', pstart = '" + pstart + "', pstop = '" + pstop + "' WHERE id = '" + dataGridView.CurrentCell.Value + "'";
cmdnew.ExecuteNonQuery();
conn.Close();
}
private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
MySqlConnection conn = DBUtils.GetDBConnection();
conn.Open();
MySqlCommand feedstartzeit = conn.CreateCommand();
feedstartzeit.CommandText = "SELECT astart FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime start = Convert.ToDateTime(feedstartzeit.ExecuteScalar());
textBoxstartzeit.Text = start.ToString("yyyy-MM-dd HH:mm:ss");
MySqlCommand feedstopzeit = conn.CreateCommand();
feedstopzeit.CommandText = "SELECT astop FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime stop = Convert.ToDateTime(feedstopzeit.ExecuteScalar());
textBoxstopzeit.Text = stop.ToString("yyyy-MM-dd HH:mm:ss");
MySqlCommand feedstartpause = conn.CreateCommand();
feedstartpause.CommandText = "SELECT pstart FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime startpause = Convert.ToDateTime(feedstartpause.ExecuteScalar());
textBoxstartpause.Text = startpause.ToString("yyyy-MM-dd HH:mm:ss");
MySqlCommand feedstoppause = conn.CreateCommand();
feedstoppause.CommandText = "SELECT pstop FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime stoppause = Convert.ToDateTime(feedstoppause.ExecuteScalar());
textBoxstoppause.Text = stoppause.ToString("yyyy-MM-dd HH:mm:ss");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Bitte ID auswählen", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Button4 is the upload new data and the dataGridView part is filling the textBoxes with a preformated datetime that later get uploaded by button4

Your date time format should be your server date time format, if you want to use datetime then you should use datetime picker so you don't need to convert into datetime.

Allright, the by Jon Skeet suggested parametered sql request solved the problem.

Related

c# Insert data into MySQL database using parameters

This probably a simple solution, but I've got a deadline to catch and I don't know the exact problem here.
So here's the deal, I'm trying to update my table using this piece of code:
private void btn_opslaan_Click(object sender, EventArgs e)
{
string opleidingsid = "Select OpleidingsID From opleidingen Where Opleidingsnaam = '" + cb_opleiding.Text + "'";
MySqlCommand cmdid = new MySqlCommand(opleidingsid, dbconnect.connection);
dbconnect.OpenConnection();
MySqlDataReader reader = cmdid.ExecuteReader();
reader.Read();
int oplid = (int)reader.GetValue(0);
cmdid.Dispose();
reader.Close();
sql = "UPDATE leerlingen SET Naam = '_naam', Adres = '_adres', Woonplaats = '_woonplaats', Postcode = '_postcode', Email = '_email', Telefoonnummer = '_telefoonnummer', Klas = '_klas', Ovnummer = '_ovnummer', OpleidingsID = '_opleidingsid', Startdatum = '_startdatum', Einddatum = '_einddatum' WHERE LeerlingID = '_leerlingid'";
// sql = "UPDATE leerlingen set Naam = '" + txt_naam.Text + "', Adres = '" + txt_adres.Text + "', Woonplaats = '" + txt_woonplaats.Text + "', Postcode = '" + txt_postcode.Text + "', Email = '" + txt_email.Text + "', Telefoonnummer = '" + txt_telefoonnumer.Text + "', Klas = '" + txt_klas.Text + "', Ovnummer = '" + txt_ovnummer.Text + "', OpleidingsID = '" + oplID + "', Startdatum = '"+mc_startdatum.SelectionStart.Date.ToString()+"', Einddatum = '"+ mc_einddatum.SelectionStart.Date.ToString() +"' WHERE LeerlingID = '" + Int32.Parse(lbl_leerlingid.Text) + "'";
MySqlCommand cmd = new MySqlCommand(sql, dbconnect.connection);
cmd.Parameters.AddWithValue("_naam", txt_naam.Text);
cmd.Parameters.AddWithValue("_adres", txt_adres.Text);
cmd.Parameters.AddWithValue("_woonplaats", txt_woonplaats.Text);
cmd.Parameters.AddWithValue("_postcode", txt_postcode.Text);
cmd.Parameters.AddWithValue("_email", txt_email.Text);
cmd.Parameters.AddWithValue("_telefoonnummer", txt_telefoonnumer.Text);
cmd.Parameters.AddWithValue("_klas", txt_klas.Text);
cmd.Parameters.AddWithValue("_ovnummer", txt_ovnummer.Text);
cmd.Parameters.AddWithValue("_opleidingsid", oplid);
cmd.Parameters.AddWithValue("_startdatum", mc_startdatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_einddatum", mc_einddatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_leerlingid", int.Parse(lbl_leerlingid.Text));
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("opslaan gelukt");
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
throw;
}
dbconnect.CloseConnection();
this.Close();
}
I've already tried without the single quotes, it would give me the error that colomn '_leerlingid' does not exist, but that is the parameter...
Now, I dont get any errors, but it wouldn't update my database.
Any help please
P.S. Ignore the sql injection please, before this , i didn't knew better before I found out about parameters.
Try replacing your parameters with the # symbol and remove the single quotes, like this:
SQL = "UPDATE leerlingen SET Naam = #naam, Adres = #adres";
cmd.Parameters.AddWithValue("#naam", txt_naam.Text);
cmd.Parameters.AddWithValue("#adres", txt_adres.Text);
I think what you did wrong is you mustn't initialize your MySqlCommand like that. It must be like this..
MySqlCommand cmd;
cmd = dbconnect.createCommand();
cmd.CommandText = "UPDATE tableName SET firstname=#firstname, lastname=#lastname where id=#id";
cmd.Parameters.AddWithValue("#id", idTxt.Text);
cmd.Parameters.AddWithValue("#firstname", fName.Text);
cmd.Parameters.AddWithValue("#lastname", lName.Text);
cmd.ExecuteNonQuery();
when I creating a new data in c#, I make it like this ..
//values
String a = "COL1ROW1", b = "COL1ROW2";
//this is the code for mysql
String query = "Insert Into tableName(Column1, Column2)values('" + a + "','" + b + "')";
//conn is your mysqlconnection
MySqlCommand cmd = new MySqlCommand(query, conn);
//then execute it
cmd.ExecuteNonQuery();

Showing Date only from SQL Database

I am sending Date from WPF to ModelClass by this method.......
private void buttonNTSave_Click(object sender, RoutedEventArgs e)
{
ModelClass model = new ModelClass();
model.TaskInsertion(textBoxNTSubject.Text, textBoxNTType.Text, Convert.ToDateTime(datePickerNT.SelectedDate), textBoxNTTitle.Text, textBoxNTDetail.Text);
}
The Date is being inserted in database by this method...
public void TaskInsertion(string subject, string type, DateTime dueDate, string title, string detail)
{
SqlConnection conn = new SqlConnection(connectionString);
try
{
string query = "INSERT INTO Tbl_Task (Email, Subject, Type, DueDate, Title, Detail) VALUES ('" + userEmail + "', '" + subject + "' , '" + type + "', '" + dueDate.Date + "', '" + title + "', '" + detail + "')";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
conn.Close();
}
}
But Whenever I try to retrieve only Date from Database to a DataGrid, still the Time with Date is showing..
public DataTable OverDueCurrentTask()
{
SqlConnection conn = new SqlConnection(connectionString);
try
{
DateTime DateToday = DateTime.UtcNow.Date;
string query = "DECLARE #sDate Date SET #sDate = '" + DateToday.Date + "' SELECT Title, Subject, Type, DueDate FROM Tbl_Task WHERE DueDate >= #sDate";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter dataAdp = new SqlDataAdapter(cmd);
DataTable dataTbl = new DataTable("Tbl_Task");
dataAdp.Fill(dataTbl);
dataAdp.Update(dataTbl);
return dataTbl;
}
catch (Exception e)
{
conn.Close();
return null;
}
}
How to show Date without showing the Time?
N.B. In Database, DueDate is a Date Type column.
You need to cast DueDate column cast([DueDate] as date) > = #sDate. While sDate is already declared as date.
string query = #"DECLARE #sDate Date SET #sDate = '" + DateToday.Date + "'
SELECT Title, Subject, Type, cast([DueDate] as date) as DueDate FROM Tbl_Task
WHERE cast([DueDate] as date) >= #sDate";
Although it completes answer but you need to make subtle changes in the code, to avoid SQL injection attacks. Use SqlCommand Parameters. Add using blocks in the code.
I'm sure you can do this in C# as well. In the SQL query, you can use:
select cast([date] as date) as dateonly
To convert the datetime to a date.
The following Edit was provided by Dan Guzman:
The C# code to build the query string needed for the application is:
string query = "DECLARE #sDate Date SET #sDate = '" + DateToday.Date + "' SELECT Title, Subject, Type, CAST(DueDate AS date) AS DueDate FROM Tbl_Task WHERE DueDate >= #sDate;";

Getting Date from database in a string

I am trying to get date from my database into a string and comparing it with the today's date to perform some operation.
What I did as a solution but still the label isn't displaying the messages.
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("Files/" + FileName));
string FilePath = "Files/" + FileName;
//SqlCommand cmd = new SqlCommand();
DAL obj = new DAL();
using (SqlConnection conn = obj.openCon())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime() ;
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if (duedate != null && today.Date > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift + "', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
}
}
You have to get DueDate from tbl_AssignmentUpload1 .
For example :
string strSQL = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like #AssignmentTitle ";
(SqlCommand myCommand = new SqlCommand(strSQL, cnn)) // Cnn is your sql connection
{
myCommand.Parameters.AddWithValue("#AssignmentTitle", AssignmentTitle );
using (SqlDataReader reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
DateTime today1 = Convert.ToDateTime(reader["DueDate "].ToString());
}
}
}
After this you can do your insert statement
Try something like this. Ok updated with the fix for duedate.
using (SqlConnection conn = SQL.GeSQLConnection())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime();
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if(duedate != null && DateTime.Today > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift +"', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
else
{
lbl_uploaded.Text = "No Due date was selected for the given assesment title";
}
}

UPDATE query not working with date field

string date=
DateTime.Now.ToString("d.M.yyyy",System.Globalization.DateTimeFormatInfo.InvariantInfo);
String MyString = #"UPDATE cas SET Odhod= '" + label1.Text + "'
WHERE sifra = " + textBox1.Text + " and Datum = "+date+"";
When I do this update without Datum (German for "date") it works, but with Datum it doesn't work. I'm connected to an Accesss database, and the type of the table field Datum is Date/Time.
Here is the program: https://www.dropbox.com/s/hx4zduvul8mh2uy/8.4.zip
Pictre of problem: http://img43.imageshack.us/img43/5189/errorbh.jpg
Use a parametrized query. You will not have to worry about date formats and it will make your query SQL-injection-safe.
string fileName = #"C:\mydb.accdb";
string query = "UPDATE cas SET Odhod = ? WHERE sifra = ? AND Datum = ?";
using (OleDbConnection conn = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName)) {
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue("?", label1.Text);
cmd.Parameters.AddWithValue("?", textBox1.Text);
cmd.Parameters.AddWithValue("?", date);
conn.Open();
cmd.ExecuteNonQuery();
}
missing some apostrophes?
String MyString = #"UPDATE cas SET Odhod= '" + label1.Text + "'
WHERE sifra = " + textBox1.Text + " and Datum = '"+date+"'";

code executing date 1st jan on 31st jan DateTime.Add

I have this code for sending birthday reminder e-mail. It is executing fine for every date other than 1st jan of every year. The E-mail which is to be sent on 1st jan is actually sent on 31 jan even when in database it is 1 jan and also variable is reading it as 1 jan and not 31 jan.
Code is:
public void birthdayReminder(string month)
{
try
{
SqlConnection con;
SqlCommand cmdReminder;
SqlDataReader userReminder;
bool result = false;
string todaydate = "";
DateTime now = DateTime.Now.AddDays(1);
todaydate = now.ToString("dd", CultureInfo.InvariantCulture);
con = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
con.Open();
cmdReminder = con.CreateCommand();
cmdReminder.CommandText = "select staffid, staffmonth, staffdate from tbstaff where staffmonth='" + month + "' and staffdate='" + todaydate + "' and staffcurrstatus='Active'";
userReminder = cmdReminder.ExecuteReader();
//userReminder.Read();
result = userReminder.HasRows;
while (userReminder.Read())
{
try
{
SqlConnection con1;
con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
con1.Open();
SqlDataReader rdr;
SqlCommand cmdRemUpd = con1.CreateCommand();
cmdRemUpd.CommandText = "select * from tbl_BirthdayReminder where staffid='" + userReminder.GetInt32(0) + "' and year='" + DateTime.Today.Year.ToString() + "'";
rdr = cmdRemUpd.ExecuteReader();
bool res = rdr.HasRows;
if(!res)
sendBirthdayEmail(userReminder.GetInt32(0));
con1.Close();
}
catch (Exception e1) { }
}
userReminder.Close();
con.Close();
}
catch (SqlException ex) { }
}
protected void sendBirthdayEmail(int id)
{
DataTable dt = new DataTable();
try
{
SqlDataAdapter adp = new SqlDataAdapter("select * from tbstaff where staffid='" + id + "'", ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
adp.Fill(dt);
string name=dt.Rows[0]["stafffname"].ToString()+' '+dt.Rows[0]["stafflname"].ToString();
string acmng = dt.Rows[0]["staffacmng"].ToString();
SqlConnection con;
SqlCommand cmd;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "select emailAddress from tbuser where firstName='" + acmng + "'";
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
string to= dr.GetValue(0).ToString();
con.Close();
Configuration configurationFile = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~\\Web.config");
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
string username = "";
string password = "";
string fromAddress = "";
int port = 0;
string host = "";
if (mailSettings != null)
{
port = mailSettings.Smtp.Network.Port;
host = mailSettings.Smtp.Network.Host;
password = mailSettings.Smtp.Network.Password;
username = mailSettings.Smtp.Network.UserName;
fromAddress = username;
}
string Aliasname = System.Configuration.ConfigurationManager.AppSettings["Alias"].ToString();
string body = "";
SmtpClient emailclient = new SmtpClient();
string path = "http://www.columbuscorp.com/sat/images/happybirthday.jpg";
body += "<html><body>";
body += "Hello <br /><br />";
body += "Please send birthday Card to " + name + " as his/her Birthday Date is on " + dt.Rows[0]["staffmonth"].ToString() + " " + dt.Rows[0]["staffdate"].ToString() + "<br/>";
body +="<img src=" + path;
body += " width=672 height=491></img>";
body += "<br /><br />Thanks from SAT Admin";
body += "</body></html>";
try
{
SqlConnection con1;
con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
con1.Open();
SqlCommand cmdRemUpd = con1.CreateCommand();
cmdRemUpd.CommandText = "insert into tbl_BirthdayReminder(staffid,year) values('" + id + "','" + DateTime.Today.Year.ToString() + "')";
cmdRemUpd.ExecuteNonQuery();
con1.Close();
}
catch (Exception e1) { }
The date you are looking at is always one day in the future:
DateTime now = DateTime.Now.AddDays(1);
That means on December 31st you are looking at a date in the next year. On the other hand this will use the "old" year, not the new one
cmdRemUpd.CommandText = "select * from tbl_BirthdayReminder where staffid='" + userReminder.GetInt32(0) + "' and year='" + DateTime.Today.Year.ToString() + "'";
So you are looking up a record that indeed does exist (last year's birthday reminder) hence the birthday reminder is not sent - it should be the same date as above I assume, so rather:
cmdRemUpd.CommandText = "select * from tbl_BirthdayReminder where staffid='" + userReminder.GetInt32(0) + "' and year='" + now.Year.ToString() + "'";

Categories

Resources