I'm doing a registration form in c#
the code is working really well, but the the problem is even if the username
is already exist in the database it's still able to duplicate username.
How can i add a restriction for having a duplicate value for username?
So here is my code ps. i didn't add the exception because it's too long.
string condense = "datasource=localhost;port=3306;username=root;password=''";
string milk = "insert into empaccount.empinfo(IDNUMBER,email,username,password,firstname,lastname,cnumber) values ('" + this.idnumber.Text + "','" + email.Text + "','" + username.Text + "','" + password.Text + "','" + firstname.Text + "','" + this.lastname.Text + "','" + contactno.Text + "');";
MySqlConnection conDatabase = new MySqlConnection(condense);
MySqlCommand cmdDatabase = new MySqlCommand(milk, conDatabase);
MySqlDataReader myReader;
if (string.IsNullOrEmpty(idnumber.Text))
{
idnumber.Text = " Please generate an id number";
}
else
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("You're Registered!", "Successful!", MessageBoxButtons.OK, MessageBoxIcon.Information);
while (myReader.Read())
{
}
}
You need to add a unique limitation (constraint) to your table, using whatever database editor you used to create it. Then, catch an exception thrown by your application if the username is taken.
Basically, if there is some username already there, and you have a unique constraint on the username field in the table, your program will throw an exception when you try to add to it. Here is an example:
Also, if you are doing an insert query, you don't need to ExecuteRead(). Just do ExecuteNonQuery() and it will run the query without needing to return anything.
string condense = "datasource=localhost;port=3306;username=root;password=''";
string milk = "insert into empaccount.empinfo(IDNUMBER,email,username,password,firstname,lastname,cnumber) values ('" + this.idnumber.Text + "','" + email.Text + "','" + username.Text + "','" + password.Text + "','" + firstname.Text + "','" + this.lastname.Text + "','" + contactno.Text + "');";
MySqlConnection conDatabase = new MySqlConnection(condense);
MySqlCommand cmdDatabase = new MySqlCommand(milk, conDatabase);
MySqlDataReader myReader;
if (string.IsNullOrEmpty(idnumber.Text))
{
idnumber.Text = " Please generate an id number";
}
else
{
conDatabase.Open();
try {
cmdDatabase.ExecuteNonQuery();
}
catch {
//Username is taken
}
MessageBox.Show("You're Registered!", "Successful!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Related
I am having issues adding dates/times to Microsoft Access, this is my code:
private void submit_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into DailyLog (EmployeeID,BusNumber,RouteID,DestinationID,ActivityID,Date,MilesDriven,GasInGallons,Comments) values('"+ employee.SelectedValue + "','" + bus.SelectedValue + "','" + route.SelectedValue + "','" + dest.SelectedValue + "','" + activity.SelectedValue + "','" + theDate.Value.ToString("MM/dd/yyyy") + "','" + miles.Value + "','" + gas.Value + "','" + comments.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Your log has been submitted.");
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Err: " + ex);
connection.Close();
}
}
It is giving me a syntax error for the "Date" only. What should I do? I've tried fixing up the properties, making it a short date, general date, etc. Nothing seems to be working for me.
Exact Error:
Try parameterizing your command. This will take care of any potential SQL injection problems as well as correctly formatting the values for the DBMS.
string commandText = "insert into DailyLog (EmployeeID,BusNumber,RouteID,DestinationID,ActivityID,Date,MilesDriven,GasInGallons,Comments) values(#employee, #bus, #route, #dest, #activity, #theDate, #miles, #gas, #comments)";
using (OleDbCommand command = new OleDbCommand(commandText, connection)) {
// add parameters
command.Parameters.Add(new OleDbParameter("#employee", OleDbType.Integer));
command.Parameters.Add(new OleDbParameter("#theDate", OleDbType.DBDate));
// set parameter valuess
command.Parameters["#employee"] = employee.SelectedValue;
command.Parameters["#theDate"] = theDate.Value;
// execute command
command.ExecuteNonQuery();
}
Updated to remove AddWithValue.
I want to connect a Windows Form app with SQL Server and insert values from the app textboxes to a database. When the button is clicked, I receive an error:
Incorrect syntax near the keyword "Group".
What is the problem? How can I insert this data?
private void button1_Click(object sender, EventArgs e)
{
try
{
string myconnection = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=StudBase;Integrated Security=True";
string Query = "Insert Into StudentInfo (StudentID, Name,Surname,Group,Course,City,Sector,Average rating) values('" +this.textBox1.Text+"','" + this.textBox2.Text + "','" + this.textBox4.Text + "','" + this.textBox6.Text + "','" + this.textBox8.Text + "','" + this.textBox3.Text + "','" + this.textBox5.Text + "','" + this.textBox3.Text + "');";
SqlConnection Myconn = new SqlConnection(myconnection);
SqlCommand Mycom = new SqlCommand(Query, Myconn);
SqlDataReader Reader1;
Myconn.Open();
Reader1 = Mycom.ExecuteReader();
MessageBox.Show("Save data");
while (Reader1.Read())
{
}
Myconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Use this for your query statement -
string Query = "Insert Into StudentInfo (StudentID,[Name],Surname,[Group],Course,City,Sector,[Average rating]) values('" +this.textBox1.Text+"','" + this.textBox2.Text + "','" + this.textBox4.Text + "','" + this.textBox6.Text + "','" + this.textBox8.Text + "','" + this.textBox3.Text + "','" + this.textBox5.Text + "','" + this.textBox3.Text + "');";
Use [] for reserved keywords in SQL. Also the last column Average rating was not covered with [], as this column name has space then it should be quoted in [].
It's my first time working with SQL Server and I can't find a helpful tutorial. I am trying to get information from the UI (infos about a contact) and save it to the database (localdb in Visual Studio) then I'd like to get the id of the added contact. I use the following code:
SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = E:\\c#\\contact2\\contact2\\contactbase.mdf;Integrated Security=True");
String query = "INSERT INTO contacts(Nom,Adresse,Tel,Email,Sweb) output Inseted.Id_Contact VALUES ('" + contact.Text + "','" + adr.Text + "','" + tlphn.Text + "','" + mail.Text + "','" + site.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
int id = 0;
id = (int)cmd.ExecuteScalar();
if (con.State == System.Data.ConnectionState.Open)
{
con.Close();
}
But it's not working, I get this exeption:
{"The multi-part identifier \"Inseted.Id_Contact\" could not be bound."}
and I don't know how to fix it.
Remark: there's is an auto_incrment for the id could you help me please
It should be output Inserted.Id_Contact ,in your code has a spelling mistake on Inserted
INSERT INTO contacts(Nom,Adresse,Tel,Email,Sweb) output Inserted.Id_Contact VALUES ('" + contact.Text + "','" + adr.Text + "','" + tlphn.Text + "','" + mail.Text + "','" + site.Text + "')";
i have a program that insert a list of field into the database. When i use my own computer to insert the datetime field it looks completing fine. however, when i insert it using a windows 7 chinese edition, the field become 0000-00-00 00:00:00
this is the command
MySqlCommand myCommand4 = new MySqlCommand("Insert into OrderRecords_table values('" + OrderIDLabel.Text + "','" + customerCode + "','" + customer + "','" + TelComboBox.Text + "','" + LicenseComboBox.Text + "','" +
DriverComboBox.Text + "','" + AddressComboBox.Text + "','" + LocationTypeComboBox.Text + "','" + PickupComboBox.Text + "','" + CustomerTypeLabel.Text + "','" +
Convert.ToDecimal(TotalPriceLabel.Text) + "','" + status + "','" + note + "','" + sandReceiptNo + "','" + createtiming + "','" + Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) + "')", myConnection);
myCommand4.ExecuteNonQuery();
i know it looks a bit messy, but the part where it says
STR_TO_DATE('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','%Y/%M/%d /%H/%m/%s'))"
is the part where i insert the current datetime. it works just fine when i use english version of windows, but whenever i use chinese edition, it isnert 0000-00-00 00:00:00 instead of the actual time, i have tried to change the format for showing dates in control panel, but it is still having the same problem.
anyone knows what the problem would be ?
Thanks
edited my code
var sql = "insert into OrderRecords_table values(#OrderID, #customercode, #customer, #PhoneNumber, #license, #driver, #address, #type, #pickupLocation, #PaymentMethod, #totalPrice, #status, #notes, #sandreceiptNo,#createTime, #EditTime)";
using (var myCommand4 = new MySqlCommand(sql, myConnection))
{
myCommand4.Parameters.AddWithValue("#orderId", MySqlDbType.VarChar).Value = OrderIDLabel.Text;
myCommand4.Parameters.AddWithValue("#customercode", MySqlDbType.VarChar).Value = customerCode;
myCommand4.Parameters.AddWithValue("#customer",MySqlDbType.VarChar).Value = customer;
myCommand4.Parameters.AddWithValue("#PhoneNumber", MySqlDbType.VarChar).Value =TelComboBox.Text;
myCommand4.Parameters.AddWithValue("#license", MySqlDbType.VarChar).Value = LicenseComboBox.Text;
myCommand4.Parameters.AddWithValue("#driver", MySqlDbType.VarChar).Value = DriverComboBox.Text;
myCommand4.Parameters.AddWithValue("#address", MySqlDbType.VarChar).Value = AddressComboBox.Text;
myCommand4.Parameters.AddWithValue("#Type", MySqlDbType.VarChar).Value = LocationTypeComboBox.Text;
myCommand4.Parameters.AddWithValue("#pickupLocation", MySqlDbType.VarChar).Value = PickupComboBox.Text;
myCommand4.Parameters.AddWithValue("#PaymentMethod", MySqlDbType.VarChar).Value = CustomerTypeLabel.Text;
myCommand4.Parameters.AddWithValue("#totalPrice", MySqlDbType.Decimal).Value = Convert.ToDecimal(TotalPriceLabel.Text);
myCommand4.Parameters.AddWithValue("#status", MySqlDbType.VarChar).Value = status;
myCommand4.Parameters.AddWithValue("#notes", MySqlDbType.VarChar).Value =status;
myCommand4.Parameters.AddWithValue("#sandreceiptNo", MySqlDbType.VarChar).Value = sandReceiptNo;
myCommand4.Parameters.AddWithValue("#createTiming", MySqlDbType.DateTime).Value = createtiming;
myCommand4.Parameters.AddWithValue("#EditTime", MySqlDbType.DateTime).Value = DateTime.Now;
myCommand4.ExecuteNonQuery();
its saying that i have some invalid input, but i have checked a few times that all the fields are asigned to the correct type.. . don't know what is happening
I've rewritten your code to a more standardized implementation (with best practices). Note that I've pulled your query out into a separate variable to let the code and query become more readable.
var sql = "insert into orderrecords_table values " +
"(#orderId, " +
" #customercode, " +
" #customer, " +
" #telephone, " +
" #license, " +
" #driver, " +
" #address " +
" #locationType, " +
" #pickup, " +
" #customerType, " +
" #totalPrice, " +
" #status, " +
" #note, " +
" #sandreceiptNo, " +
" #createTiming, " +
" #currentTime) ";
using (var myCommand4 = new MySqlComm## Heading ##and(sql, connection))
{
myCommand4.Parameters.AddWithValue("#orderId", OrderIDLabel.Text) ;
myCommand4.Parameters.AddWithValue("#customercode", customerCode);
myCommand4.Parameters.AddWithValue("#customer", customer);
myCommand4.Parameters.AddWithValue("#telephone", TelComboBox.Text);
myCommand4.Parameters.AddWithValue("#license", LicenseComboBox.Text);
myCommand4.Parameters.AddWithValue("#driver", DriverComboBox.Text);
myCommand4.Parameters.AddWithValue("#address", AddressComboBox.Text);
myCommand4.Parameters.AddWithValue("#locationType", LocationTypeComboBox.Text);
myCommand4.Parameters.AddWithValue("#pickup", PickupComboBox.Text);
myCommand4.Parameters.AddWithValue("#customerType", CustomerTypeLabel.Text);
myCommand4.Parameters.AddWithValue("#totalPrice", Convert.ToDecimal(TotalPriceLabel.Text));
myCommand4.Parameters.AddWithValue("#status", status);
myCommand4.Parameters.AddWithValue("#note", status);
myCommand4.Parameters.AddWithValue("#sandreceiptNo", sandReceiptNo);
myCommand4.Parameters.AddWithValue("#createTiming", createtiming);
myCommand4.Parameters.AddWithValue("#currentTime", DateTime.Now);
myCommand4.ExecuteNonQuery();
}
MySqlCommand Insert = new MySqlCommand("INSERT INTO [TABLE] ([Date], [TEXT]) VALUES(#Date, #Text) ", myConnection);
Insert.CommandTimeout = 60; //if you need
Insert.Parameters.AddWithValue("#Date", DateTime.Now);
Insert.Parameters.AddWithValue("#Text", "Hello word!");
Insert.ExecuteNonQuery();
Insert.Dispose();
I have an Access DB connected to my form with that code ( C# ) :
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB\DataMG.mdb";
try
{
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT into Prodotti ([Codice],[Descrizione],[Marchio],[Deposito],[Note],[NumeroProdotti],[PrzListinoBase_Aq],[PrzListinoBase_Ve],[Categoria],[Posizione],[Disponibilita],[QtaVenduta],[QtaAcquistata]) VALUES ('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "'," + this.Note.Text + "," + this.NumProd.Text + "," + this.PrzListAcq.Text + "," + this.PrzListVen.Text + ",'" + this.Categ.Text + "','" + this.Posiz.Text + "'," + this.Disp.Text + "," + this.QtaVen.Text + "," + this.QtaAcq.Text + ")";
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
// MessageBox.Show("Connessione Fallita!");
conn.Close();
}
finally
{
conn.Close();
}
The error I get when i click the buttton is this one :
Any ideas?
You are missing single quotations in Insert Statement where you are assigning values to columns. Your code is vulnerable so should avoid this here is a useful link.
Are Parameters really enough to prevent Sql injections?
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB \DataMG.mdb";
try
{
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT into Prodotti (Codice,Descrizione,Marchio,Deposito,Note,NumeroProdotti,PrzListinoBase_Aq,PrzListinoBase_Ve,Categoria,Posizione,Disponibilita,QtaVenduta,QtaAcquistata) VALUES('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "','" + this.Note.Text + "','" + this.NumProd.Text + "','" + this.PrzListAcq.Text + "','" + this.PrzListVen.Text + "','" + this.Categ.Text + "','" + this.Posiz.Text + "','" + this.Disp.Text + "','" + this.QtaVen.Text + "','" + this.QtaAcq.Text + "')";
conn.Open();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
// MessageBox.Show("Connessione Fallita!");
conn.Close();
}
finally
{
conn.Close();
}
I don't know italian (is that even the language? :) ) but from the look of it it could very well be a culture settings problem. If, for example, one of your fields is numeric then the database might expect a different decimal separator than the one in use in your UI.
Also your actual design seems very vulnerable to SQL Injection Attacks.
For these reasons, my suggestion is that you use the command's Parameters collection to set your values rather than trying to pass in a concatenated string.
I don't read the language you are posting the error from, however, it looks like a syntax error somewhere in your SqlCommand.
First thing I would suggest is wrapping your connection and command in using blocks to make sure they get disposed of correctly.
Then ALWAYS user parametarized SQL Commands to avoid SQL Injection:
using (var conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB\DataMG.mdb"))
using (var cmd = new System.Data.OleDb.OleDbCommand())
{
cmd.CommandText = "INSERT INTO TableName (column1, column2, column3) VALUES (#Value1, #Value2, #Value3)";
cmd.Parameters.AddWithValue("#Value1", this.TextBox1.Text);
cmd.Parameters.AddWithValue("#Value2", this.TextBox2.Text);
cmd.Parameters.AddWithValue("#Value3", this.TextBox3.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
Generally speaking, using parameters eliminates syntax errors because it makes the command much easier to read in it's string representation.
I think you may be missing single quotes around some of your text qualifiers in your INSERT statement.
"INSERT into Prodotti ([Codice],[Descrizione],[Marchio],[Deposito],[Note],[NumeroProdotti],[PrzListinoBase_Aq],[PrzListinoBase_Ve],[Categoria],[Posizione],[Disponibilita],[QtaVenduta],[QtaAcquistata]) VALUES ('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "'," + this.Note.Text + "," + this.NumProd.Text + "," + this.PrzListAcq.Text + "," + this.PrzListVen.Text + ",'" + this.Categ.Text + "','" + this.Posiz.Text + "'," + this.Disp.Text + "," + this.QtaVen.Text + "," + this.QtaAcq.Text + ")";
Consider using a parameterized query rather than building your query string by hand. Not only is it safer, but it can help to weed out these kinds of errors which can be tedious to debug.
eg.
String StrSQL = "INSERT INTO tblLog ([Part_Number],[Quantity],[Date],[LOC_Warehouse],[LOC_Row],[LOC_Section],[LOC_Level],[LOC_Bin],[Stock_Added],[Stock_Removed],[Quarantine_Set],[Quarantine_Removed])"
+ "VALUES(#Part_Number, #Quantity, #Date, #Warehouse, #Row, #Section, #Level, #Bin, #Stock_Added, #Stock_Removed, #Quarantine_Set, #Quarantine_Removed)";
SqlConnection conn = new SqlConnection(WHITS.Properties.Settings.Default.LocalConnStr);
SqlCommand cmd = new SqlCommand(StrSQL, conn);
cmd.Parameters.AddWithValue("#Part_Number", Part_Number);
cmd.Parameters.AddWithValue("#Quantity", Quantity);
cmd.Parameters.AddWithValue("#Date", DateTime.Now);
//More Parameters... Skipped for brevity.
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Open your connection earlier. Also, use "using". Here's how I would do it:
try
{
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB\DataMG.mdb";
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString))
{
conn.Open();
string insertQuery = "INSERT into Prodotti ([Codice],[Descrizione],[Marchio],[Deposito],[Note],[NumeroProdotti],[PrzListinoBase_Aq],[PrzListinoBase_Ve],[Categoria],[Posizione],[Disponibilita],[QtaVenduta],[QtaAcquistata]) VALUES ('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "'," + this.Note.Text + "," + this.NumProd.Text + "," + this.PrzListAcq.Text + "," + this.PrzListVen.Text + ",'" + this.Categ.Text + "','" + this.Posiz.Text + "'," + this.Disp.Text + "," + this.QtaVen.Text + "," + this.QtaAcq.Text + ")";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(insertQuery, conn);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
}
}
Edit: My bad... the code I was referencing was filling a DataAdapter, which doesn't require a call to connection.Open(). Regular querying does. My apologies... I have edited my suggestion.