1

So I have another problem doing my school project. FYI, we don't use sql-parameters and didn't learn how to use them as of yet.

I am trying to insert a birthday into the sql database but I tried everything but there is always a data type mismatch.

Can you guys help me out (without changing the structure of the code)? You can look it up by searching "birthday" as everything else has German names.

I would really appreciate your help as I'm really desperate. EDIT: There is a textbox, where user are supposed to type in the birthday. That's where I get the data.

EDIT: I removed all other unnecessary strings etc.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;

public class webUser
{

private DateTime _birthday;

public webUser()
{
    //
    // TODO: Add constructor logic here
    //

public DateTime birthday
{
    get { return _birhday; }
    set { _birthday= value; }
}

public bool checkUser(string eMail)
{
    string sql = "SELECT eMail, kennwort FROM Benutzerdatenbank WHERE eMail ='" + eMail + "'";
    string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Benutzerdatenbank.accdb");

    OleDbConnection con = new OleDbConnection(conStr);
    con.Open();
    OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
    DataSet ds = new DataSet();
    da.Fill(ds);
    con.Close();

    if (ds.Tables[0].Rows.Count == 1)
        return true;
    else
        return false;
}

public bool addUser(string eMail, string kennwort, string vorname, string zuname, string telefonnummer, string strasse, string plz, string ort, string firma, string titel, DateTime birthday)
{
    if (this.checkUser(eMail) == true)

    {
        return false; 

    }

    else
    {

        string zeichen =   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghjiklmnopqrstuvwxyz0123456789";
        string aktivierungscode = "";
        Random rnd = new Random();
        for (int i = 1; i < 62; i++)
        {
            aktivierungscode = aktivierungscode + zeichen.Substring(rnd.Next(0, zeichen.Length - 1), 1);
        }

        string sql = "INSERT INTO Benutzerdatenbank (eMail, kennwort, Titel, Vorname, Zuname, Firma, birthday, Telefonnummer, Strasse, PLZ, Ort, aktivierungscode) VALUES ('" +
        eMail + "','" + kennwort + "','" + titel + "','" + vorname + "','" + zuname + "','" + firma +  "','" + birthday+ "','" + telefonnummer + "','" + strasse + "','" + plz + "','" + ort + "','" + aktivierungscode + "');";


        string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Benutzerdatenbank.accdb");
        OleDbConnection con = new OleDbConnection(conStr);
        OleDbCommand cmd = new OleDbCommand(sql, con);

        con.Open();
        cmd.ExecuteNonQuery(); 
        con.Close();
        return true;
    }
}

public void ReadUser(string eMail, string kennwort)
{
    string sql = "SELECT * FROM Benutzerdatenbank WHERE eMail='" + eMail + "' AND kennwort ='" + kennwort + "'";
    string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Benutzerdatenbank.accdb");

    OleDbConnection con = new OleDbConnection(conStr);
    con.Open();
    OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
    DataSet ds = new DataSet();
    da.Fill(ds);
    con.Close();

    if (ds.Tables[0].Rows.Count == 1)
    {
        this.eMail = (string)ds.Tables[0].Rows[0]["eMail"];
        this.vorname = (string)ds.Tables[0].Rows[0]["Vorname"];
        this.zuname = (string)ds.Tables[0].Rows[0]["Zuname"];
        this.telefonnummer = (string)ds.Tables[0].Rows[0]["Telefonnummer"];
        this.strasse = (string)ds.Tables[0].Rows[0]["strasse"];
        this.plz = (string)ds.Tables[0].Rows[0]["PLZ"];
        this.ort = (string)ds.Tables[0].Rows[0]["ORT"];
        this.titel = (string)ds.Tables[0].Rows[0]["Titel"];
        this.firma = (string)ds.Tables[0].Rows[0]["Firma"];
        this.birthday= Convert.ToDateTime(ds.Tables[0].Rows[0]["birthday"];

    }
    else
    {
        this.eMail = "";
        this.vorname = "";
        this.zuname = "";
    }
}

}

TT.
  • 15,774
  • 6
  • 47
  • 88
Nuray
  • 15
  • 6
  • I recommend to dramatically remove code and blank lines, leaving only the absolute necessary code to help you solving the problem. – Uwe Keim Jan 17 '16 at 18:36
  • 1
    alright! will do now – Nuray Jan 17 '16 at 18:38
  • Is there a reason all your data types - even date - are STRING? Ever considered that a Date in SQL Server is a date and in your code should be a DateTime? Otherwise i fyou insist on abusing SQL - use the ISO form for dates (2016-01-22) which SQL server always understands. – TomTom Jan 17 '16 at 18:39
  • the date (birthday) is a datetime tho? – Nuray Jan 17 '16 at 18:43
  • 1
    @TomTom: It's not SQL Server, it's an Access database. AFAIK, Access uses `#mm/dd/yyyy#` as date literals. – Heinzi Jan 17 '16 at 18:44
  • @Nuray Try replacing following code fragment `"','" + birthday+ "','"` with `"','" + birthday.ToString("mm/dd/yyyy")+ "','"` – tchelidze Jan 17 '16 at 18:46
  • @tchelidze will try! thank you! – Nuray Jan 17 '16 at 18:47
  • @Nuray Read also about [SQL Injection](http://www.acunetix.com/websitesecurity/sql-injection/) and you will know why you should use parameters. – tchelidze Jan 17 '16 at 18:50
  • Now, I get the error: CS1502 and it highlights my aspx.cs saying "The best overloaded method match for 'name' has some invalid arguments" `protected void btnRegistrieren_Click1(object sender, EventArgs e) { if (mywebUser.addUser(txtFirma.Text, txteMail.Text, txtKennwort.Text, txtbirthday.Text, txtOrt.Text, txtPLZ.Text, txtStrasse.Text (etc.)) == true )` .. – Nuray Jan 17 '16 at 18:58
  • You mark a question as solved by checking the checkmark and thereby accepting the answer. **Not** by editing the title and adding SOLVED to it. – TT. Jan 17 '16 at 20:38

4 Answers4

2

FYI, we don't use sql-parameters and didn't learn how to use them as of yet.

Then learn how to use them. There is really no point in learning to do it the wrong way. Plus, using dates without parameters is actually more complicated than doing it with parameters.

Parameters are really simple. The following question contains everything you need to get started:

The only difference you need to be aware of is that OleDbCommand uses ? instead of @parameterName as the parameter placeholder in the SQL statement. The parameter name is ignored, parameters are added in the order in which the ? placeholders appear.


In your case, the relevant code would look like this:

string sql = "INSERT INTO Benutzerdatenbank (eMail, kennwort, Titel, Vorname, Zuname, Firma, birthday, Telefonnummer, Strasse, PLZ, Ort, aktivierungscode) " +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";

OleDbCommand cmd = new OleDbCommand(sql, con);

// The parameter names (first argument) are ignored, the order is important
cmd.Parameters.AddWithValue("@eMail", eMail);
...
cmd.Parameters.AddWithValue("@birthday", birthday);
...

cmd.ExecuteNonQuery(); 
Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • Ok, thanks, I will try my best to learn it by my own. Maybe I will get some extra point on the project? He is actually very knowledgable, don't know why he didn't show us the "right" way. Probably because we are stil in high school, idk. But how should I solve that date problem? – Nuray Jan 17 '16 at 18:45
  • @Nuray: I've added an example. – Heinzi Jan 17 '16 at 18:52
  • the program highlights AddWithValue saying there is no definition of it in using System.Data.OleDb.OleDbCommand - what should I do? – Nuray Jan 17 '16 at 19:19
  • @Nuray: Sorry, should have been `cmd.Parameters.AddWithValue`. – Heinzi Jan 17 '16 at 19:44
1

Format your date parameter as "year date month" with "yyyyMMdd", like: birthday.ToString("yyyyMMdd").
Otherwise, SQL Server tries to convert it from m/d/yyyy format.

string sql = "INSERT INTO Benutzerdatenbank (eMail, kennwort, Titel, Vorname, Zuname, Firma, birthday, Telefonnummer, Strasse, PLZ, Ort, aktivierungscode) VALUES ('" +
eMail + "','" + kennwort + "','" + titel + "','" + vorname + "','" + zuname + "','" + firma +  "','" + birthday.ToString("yyyyMMdd") + "','" + telefonnummer + "','" + strasse + "','" + plz + "','" + ort + "','" + aktivierungscode + "');";
Mustafa Ekici
  • 7,263
  • 9
  • 55
  • 75
  • okay, done, but there is an error on my aspx.cs - saying "the best overloaded method has some invalid arguments" marking `protected void btnRegistrieren_Click1(object sender, EventArgs e) { webUser mywebUser = new webUser(); if (mywebUser.addUser(txtFirma.Text, txteMail.Text, txtKennwort.Text, txtbirthday.Text, txtOrt.Text, txtPLZ.Text, txtStrasse.Text, txtTitel.Text, txtVorname.Text, txtZuname.Text, txtTelefonnumer.Text) == true) lblMeldung.Text = ""; else lblMeldung.Text = "";` – Nuray Jan 17 '16 at 20:00
0

It could be that the format of your DateTime object does not match what the SQL database wishes. datetime format to SQL format using C#

Community
  • 1
  • 1
Paul
  • 176
  • 3
  • 16
0

This is an example of a insertion in SQL Server with SQL language:

The table is PERSON and this is you struct:

ID, int, primary key, autoincrement

NAME, nvarchar(50), not null

BIRTHDATE, datetime

now, for insert is:

INSERT INTO PERSON (NAME, BIRTHDATE) VALUES('Jose Luis', DATETIMEFROMPARTS(1988, 7, 27, 0,0,0,0));

and for select is:

SELECT * FROM PERSON WHERE BIRTHDATE = DATETIMEFROMPARTS(1988, 7, 27, 0,0,0,0);

this code is testing in SQL Server.

The idea is that you change the value of the variable 'sql' of you code, for example push:

var bithdateformat = string.Format("DATETIMEFROMPARTS({0}, {1}, {2}, {3}, {4}, {5}, {6})", birthday.Year, birthday.Month, birthday.Day, 0, 0, 0, 0);

string sql = "INSERT INTO Benutzerdatenbank (eMail, kennwort, Titel, Vorname, Zuname, Firma, birthday, Telefonnummer, Strasse, PLZ, Ort, aktivierungscode) VALUES ('" + eMail + "','" + kennwort + "','" + titel + "','" + vorname + "','" + zuname + "','" + firma + "','" + bithdateformat + "','" + telefonnummer + "','" + strasse + "','" + plz + "','" + ort + "','" + aktivierungscode + "');";

Jose Luis
  • 37
  • 3
  • this is way too different from my code, and I am not as experienced at programming as we are in high school.... – Nuray Jan 17 '16 at 20:02