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 = "";
}
}
}
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:
Why do we always prefer using parameters in SQL statements?
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();
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 + "');";
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#
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 + "');";
Related
I also don't know how to add the values of comboboxes and gender radio buttons to the database. This is basically for a registration form to insert its values into a database. I also need to display the values of the database on the form from selecting the combobox value.
private void Btn_register_Click(object sender, EventArgs e)
{
//int regNo = Cbox_regNo.Text; //i need to get the values from the combobox
string fName = Tbox_fName.Text;
string lName = Tbox_lName.Text;
string dob = dtp_dob.Text;
string address = Tbox_address.Text;
string email = Tbox_email.Text;
string mPhone = Tbox_mPhone.Text;
string hPhone = Tbox_hPhone.Text;
string pName = Tbox_parentName.Text;
string nic = Tbox_nic.Text;
string cNumber = Tbox_cntctNumber.Text;
string connString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\abhin\\Desktop\\Final Project\\Visual Studio\\Final Project\\Final Project\\Student.mdf\";Integrated Security=True";
string Query = "insert into Registrations (regNo, firstName, lastName, dateOfBirth, gender, address, email, mobilePhone, homePhone, parentName, nic, contactNo) values('"+this.Cbox_regNo.Text+"','" + this.Tbox_fName.Text + "','" + this.Tbox_lName.Text + "','" + this.dtp_dob.Value + "','" + this.Tbox_address.Text + "','" + this.Tbox_email.Text + "','" + this.Tbox_mPhone.Text + "','" + this.Tbox_hPhone.Text + "','" + this.Tbox_parentName.Text + "','" + this.Tbox_nic.Text + "','" + this.Tbox_cntctNumber.Text + "') ;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmdDB = new SqlCommand(Query, conn);
SqlDataReader myReader;
try
{
conn.Open();
myReader=cmdDB.ExecuteReader();
MessageBox.Show("Record Added Succesfully", "Register Student", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
while (myReader.Read())
{
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
On declaring your “Query” variable you are using 12 column (regNo, firstName…) and 11 value. You need one more value
Hey My Insert Statement isn't Working I used the same code for inserting other panel data to excel sheet it's working perfectly there but when I'm trying to insert data in other sheet using second panel it's throwing exception "Insert INTO Statement is not valid" I check every single thing in this i can't find any mistake in it. I'm using OleDb For Insertion.
Here is the same code I've been using for first panel insertion.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
String filename1 = #"E:DB\TestDB.xlsx";
String connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename1 + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
OleDbConnection con = new OleDbConnection(connection);
con.Open();
int id = 4;
string user = txtMUserName.Text.ToString();
string pass = txtMPassword.Text.ToString();
string role = txtMRole.Text.ToString();
DateTime date = DateTime.Now;
string Date = date.ToString("dd/MM/yyyy");
//string Time = date.ToLongTimeString();
string Time = "3:00 AM";
String Command = "Insert into [Test$] (UserID, UserName, Password, Role, Created_Date,Created_Time) VALUES ('"
+ id.ToString() + "','"
+ user + "','"
+ pass + "','"
+ role + "','"
+ Date + "','"
+ Time + "')";
OleDbCommand cmd = new OleDbCommand(Command, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Success!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Seems like you are using a reserved name for column Password. you need to escape it with []:
string Command = "Insert into [Test$] (UserID, UserName, [Password], Role, Created_Date,Created_Time) VALUES ('"
+ id.ToString() + "','"
+ user + "','"
+ pass + "','"
+ role + "','"
+ Date + "','"
+ Time + "')";
I have a little problem with an error. but I have this command in another form and do not give me the error.
This is the code:
string select = "select CONCAT(nume,' ',prenume) from echipa where email=#EMAIL";
cmd.Connection = con;
if (bunifuCheckbox1.Checked == true)
{
con.Open();
cmd.CommandText = "Insert into clienti_fizici(nume,prenume,email,telefon,adresa,data_nasterii,data_ora,CNP,sex,judetprovenienta,temperamentclient,provenientaclient,descriere,numeagent)values('"
+ bunifuMaterialTextbox1.Text + "','" + bunifuMaterialTextbox2.Text + "','" + bunifuMaterialTextbox4.Text + "','" + bunifuMaterialTextbox8.Text + "','" + bunifuMaterialTextbox3.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd HH: mm:ss") + "','" + bunifuDatepicker1.Value.Date + "','" + bunifuMaterialTextbox11.Text + "','" + gender + "','" + bunifuMaterialTextbox12.Text + "','" + bunifuDropdown1.selectedValue + "','" + bunifuDropdown2.selectedValue
+ "','" + richTextBox1.Text + "','" + select + "')";
cmd.Parameters.AddWithValue("#EMAIL", loginform.Email);
MessageBox.Show("Datele au fost introduse in baza de date !");
cmd.ExecuteNonQuery();
con.Close();
}
and the error would be from that select.
First, you must never concatenate strings with user input to create SQL Statement. Instead, always parameterize your SQL statements. Otherwise you are risking SQL injection attacks.
Second, you can't use select inside the values clause.
What you can do add parameters or hard coded values to your select statement.
Third, SqlConnection and SqlCommand both implement the IDisposable interface and should be used as a local variable inside a using block.
A better code would look like this:
if (bunifuCheckbox1.Checked == true)
{
string sql = "Insert into clienti_fizici(nume, prenume, email, telefon, adresa, data_nasterii, data_ora, CNP, sex, judetprovenienta, temperamentclient, provenientaclient, descriere, numeagent) " +
"SELECT #nume, #prenume, #email, #telefon, #adresa, #data_nasterii, #data_ora, #CNP, #sex, #judetprovenienta, #temperamentclient, #provenientaclient, #descriere, CONCAT(nume,' ',prenume) " +
"FROM echipa where email = #EMAIL";
// Note: SqlConnection should be opened for the shortest time possible - the using statement close and dispose it when done.
using(var con = new SqlConnection(connectionString))
{
// SqlCommand is also an IDisposable and should be disposed when done.
using(var cmd = new SqlCommand(sql, con)
{
cmd.Parameters.Add("#nume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox1.Text;
cmd.Parameters.Add("#prenume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox2.Text;
//... Add the rest of the parameters here...
cmd.Parameters.Add("#EMAIL", SqlDbType.NVarChar).Value = loginform.Email;
// Why is this here? MessageBox.Show("Datele au fost introduse in baza de date !");
con.Open();
cmd.ExecuteNonQuery();
}
}
}
I wrote a SQL command to save some items in my database. But when I run it, it gives an error message:
And here is my code:
public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
{
if (beoordelingBest < beoordeling)
{
titelBest = titel;
beoordelingBest = beoordeling;
}
string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
command = new SqlCommand(queryString, con);
Can someone please help me with this? I can't figure it out.
Use parametererized queries and do not use string concatination. This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example).
If you have multiple queries each unique parameter value should have its own parameter name/value
Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable
Never reuse connections as global objects, create, use, and destroy them when needed.
Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary.
var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT #a1Voornaam, #a1Achternaam, FilmID from Films WHERE titel = #title";
using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
command.Parameters.Add(new SqlParameter("#a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
command.Parameters.Add(new SqlParameter("#achternaam", SqlDbType.VarChar){Value = achternaam});
command.Parameters.Add(new SqlParameter("#title", SqlDbType.VarChar){Value = title});
con.Open();
command.ExecuteNonQuery();
}
Perhaps one of your values is ');
That would terminate the INSERT statement early, and cause the error.
|
V
INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');
You should use SqlParameters instead of string concatenation.
Are you using TextBoxes? I can't tell for sure. Try something like this, and change to suit your specific needs.
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
try
{
string query = "insert into UserDetail(Name,Address)
values('" + txtName.Text + "','" + txtAddress.Text + "');";
SqlDataAdapter da = new SqlDataAdapter(query, con);
con.Open();
da.SelectCommand.ExecuteNonQuery();
con.Close();
lblmessage.Text = "Data saved successfully.";
}
catch
{
con.Close();
lblmessage.Text = "Error while saving data.";
}
}
I need to get the userid(primary key auto_increment) from another table(login) into userdetails table. When trying to run it I keep getting this error " incorrect integer value: 'LAST_INSERT_ID()' for column 'userid' at row 1".
I've tried to take LAST_INSERT_ID() out and run another query after query4 to insert the value into the userid but I can't get it to insert into the right row it just opens a new row.
this is the code am trying to run.
try
{
//This is my connection string i have assigned the database file address path
string MyConnection2 = "datasource=localhost;port=3310;database=e-votingsystem;username=root;password=Password12;";
//this is my insert query in which i am taking input from the user through windows forms
string Query2 = "INSERT INTO vote (username) VALUE ('" + usernameInputBox.Text + "');";
string Query3 = "INSERT INTO login (username,upassword) VALUE ('" + usernameInputBox.Text + "','" + passwordInputBox.Text + "');";
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUES ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text+"');";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query2, MyConn2);
MySqlCommand MyCommand3 = new MySqlCommand(Query3, MyConn2);
MySqlCommand MyCommand4 = new MySqlCommand(Query4, MyConn2);
MySqlDataReader MyReader2;
MySqlDataReader MyReader3;
MySqlDataReader MyReader4;
// opens new connection to database then executes command
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader(); // Here the query will be executed and data saved into the database.
while (MyReader2.Read())
{
}
MyConn2.Close();
// opens new connection to database then executes command
MyConn2.Open();
MyReader3 = MyCommand3.ExecuteReader();
while (MyReader3.Read())
{
}
MyConn2.Close();
//opens new connection to database the exexcutes command
MyConn2.Open();
MyReader4 = MyCommand4.ExecuteReader();
while (MyReader4.Read())
{
}
MyConn2.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
MessageBox.Show("Hello " + forename + surname, "read and accept the terms and conditions to continue");
//new termsAndConditionsPage().Show();
//Hide();
}
As explained in other answer, you have the LAST_INSERT_ID between single quotes and this transform it in a literal string not in a statement to execute. However also removing the quotes I am not sure that you can retrieve the LAST_INSERT_ID using a connection different from the one that originates the AUTOINCREMENT number on the login table. In any case you should use a different approach and, as a first thing, you should remove ASAP the string concatenations and use parameters (Reason: Sql Injection or SurName = O'Neill)
string Query2 = "INSERT INTO vote (username) VALUE (#uname)";
string Query3 = #"INSERT INTO login (username,upassword) VALUE (#uname, #upass);
SELECT LAST_INSERT_ID();";
string Query4 = #"INSERT INTO userdetails
(nationalinsurance,userid,forename,middlename,
surname,housenumber,street,towncity,postcode,suffix)
VALUES (#insurance, #userid, #forename, #middlename,
#surname, #housenum, #street, #town, #postcode, #suffix)";
Now open just one connection and build three commands, all between an using statement
using(MySqlConnection con = new MySqlConnection(.....constring here....))
using(MySqlCommand cmd2 = new MySqlCommand(Query2, con))
using(MySqlCommand cmd3 = new MySqlCommand(Query3, con))
using(MySqlCommand cmd4 = new MySqlCommand(Query4, con))
{
con.Open();
// Add the parameter to the first command
cmd2.Parameters.Add("#uname", MySqlDbType.VarChar).Value = usernameInputBox.Text;
// run the first command
cmd2.ExecuteNonQuery();
// Add parameters to the second command
cmd3.Parameters.Add("#uname", MySqlDbType.VarChar).Value = usernameInputBox.Text;
cmd3.Parameters.Add("#upass", MySqlDbType.VarChar).Value = passwordInputBox.Text;
// Run the second command, but this one
// contains two statement, the first inserts, the
// second returns the LAST_INSERT_ID on that table, we need to
// catch that single return
int userID = (int)cmd3.ExecuteScalar();
// Run the third command
// but first prepare the parameters
cmd4.Parameters.Add("#insurance", MySqlDbType.VarChar).Value = nationalInsuranceInputBox.Text;
cmd4.Parameters.Add("#userid", MySqlDbType.Int32).Value = userID;
.... and so on for all other parameters
.... using the appropriate MySqlDbType for the column type
cmd4.ExecuteNonQuery();
}
you current query has an error
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');SELECT LAST_INSERT_ID();"
try the attached query
In your text query string you have: "','"+"LAST_INSERT_ID()"+"','". Note that the "','"s before and after the "LAST_INSERT_ID()" are incorrectly enclosing the LAST_INSERT_ID() term in single quotes.
Try the following query:
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "',"+"LAST_INSERT_ID()"+",'" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');";