How Would I Add a Date To Microsoft Access? - c#

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.

Related

Error in SQL - No Error message - Command not executing

I am working on a database application for asset management for my company. I don't have a ton of experience with SQL or MS Access for database management. I am working on a solution for adding data to the database using C# in visual studio by having it run SQL commands. I have worked in some text boxes to reveal if my code is or is not running in different places, and I have (I think) narrowed it down to my SQL, though I don't know for sure, I haven't found much about Access and OleDb through searching.
I have altered the capitalization and phrasing, as well as the commas and quotes for my SQL code, as well as baked in places where my errors could be caught by the code.
private void SubmitButton_Click(object sender, EventArgs e)
{
try
{
//declares connection
OleDbConnection con = new OleDbConnection();
OleDbCommand command = new OleDbCommand();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\eric.varner\Documents\AssetDB.accdb";
//open connection to Database
con.Open();
StatusLabel.Text = "Connected";
//declares command type
command.Connection = con;
//SQL commands to call database to write data.
if (AssetTypeBox.Text == "iPad")
{
command.CommandText = "INSERT INTO AssetsiPad (Asset Tag, Condition, Location, Serial Number) VALUES('" + AssetBox.Text + "','" + ConditionBox.Text +
"','" + LocationBox.Text + "','" + SerialNumBox.Text + "')";
MessageBox.Show("The if statement runs fine");
}
else if (AssetTypeBox.Text == "iPhone")
{
command.CommandText = "INSERT INTO AssetsiPhone (Asset Tag, Condition, Location, Serial Number) VALUES('" + AssetBox.Text + "','" + ConditionBox.Text +
"','" + LocationBox.Text + "','" + SerialNumBox.Text + "')";
}
else if (AssetTypeBox.Text == "MR AP")
{
command.CommandText = "INSERT INTO AssetsMR (Asset Tag, Condition, Location, Serial Number, MAC Address, IP Address) VALUES('" + AssetBox.Text + "','"
+ ConditionBox.Text + "','" + LocationBox.Text + "','" + SerialNumBox.Text + "','" + MACaddressBox.Text + "','" + IPsubnetBox.Text + "')";
}
else if (AssetTypeBox.Text == "MX Security")
{
command.CommandText = "INSERT INTO AssetsMX (Asset Tag, Condition, Location, Serial Number) VALUES('" + AssetBox.Text + "','" + ConditionBox.Text + "','"
+ LocationBox.Text + "','" + SerialNumBox.Text + "',)";
}
else if (AssetTypeBox.Text == "Laptop")
{
command.CommandText = "INSERT INTO AssetsLaptop (Asset Tag, Condition, Location, Serial Number) VALUES('" + AssetBox.Text + "','" + ConditionBox.Text + "','"
+ LocationBox.Text + "','" + SerialNumBox.Text + "',)";
}
else
{
MessageBox.Show("you aren't reaching the correct statement");
}
command.ExecuteNonQuery();
//close connection to Database
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
StatusLabel.Text = "Not Connected";
MessageBox.Show("your sql didn't run correctly");
}
}
When I enter my strings correctly such as "iPad" I get the message boxes that say "The if statement runs fine" and "Your SQL didn't run correctly." The AssetTypeBox is the only thing that I have any kind of catches built into. The other fields should be able to accept any type or amount of data without issue. I hope I'm not leaving anything out.
I think the INSERT command cannot accept field names with spaces, unless you enclose them in square brackets:
[Asset Tag]
The if statement runs fine
Your SQL didn't run correctly
the above result is pretty expected. Your SQL Query gets executed when you run command.ExecuteNonQuery(); which means you don't get exception before this point.
the if statement with IPad check satisfies and MessageBox.Show("The if statement runs fine"); runs after that your code executes command.ExecuteNonQuery(); and Exception occurs.
since you have exception block, the error is handled by the code below
StatusLabel.Text = "Not Connected";
MessageBox.Show("your sql didn't run correctly");

How can i validate existing username in database using mysql in c#

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);
}

C# SQL params Insert Query not Working Properly

Okay so I am trying to use parameters in C# sql code block but I am getting #Data in my SQL table please help
string connectionString = #"Network Library=DBMSSOCN;Data Source=**********,1433;database=*******;User id=*****;Password=******;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//
// Description of SQL command:
// 1. It selects all cells from rows matching the name.
// 2. It uses LIKE operator because Name is a Text field.
// 3. #Name must be added as a new SqlParameter.
//
using (SqlCommand command = new SqlCommand(
"INSERT INTO [dbo].[event_logs] ([event_level],[date_and_time],[source],[event_id],[task_category],[event_data],[channel],[computer_id],[created_at],[updated_at])VALUES('" + entry.EntryType + "','" + entry.TimeWritten + "','" + entry.Source + "','" + entry.InstanceId + "','" + entry.Category + "',' #Data ','" + logtype + "','" + computerID + "','" + DateTime.Now.ToString() + "','" + DateTime.Now.ToString() + "')", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("#Data", entry.Message));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
}
}
}
INSERTs don't return results. Use .ExecuteNonQuery() instead of .ExecuteReader().
You are getting #Data because you SQL string is formatted like "',' #Data ','" which is wrong, it is no more a variable, it is itself a SQL String.
What you need to do is fix the SQL query from "',' #Data ','" to "', #Data ,'" it will be fine then.
using (SqlCommand command = new SqlCommand(
"INSERT INTO [dbo].[event_logs] ([event_level],[date_and_time],[source],[event_id],[task_category],[event_data],[channel],[computer_id],[created_at],[updated_at])VALUES('" + entry.EntryType + "','" + entry.TimeWritten + "','" + entry.Source + "','" + entry.InstanceId + "','" + entry.Category + "', #Data ,'" + logtype + "','" + computerID + "','" + DateTime.Now.ToString() + "','" + DateTime.Now.ToString() + "')", connection))
{
// Add new SqlParameter to the command.
command.Parameters.Add(new SqlParameter("#Data", entry.Message));
command.ExecuteNonQuery();
}
You need to specify the name and data type in the constructor, and the value in the new object:
command.Parameters.Add("#Data", SqlDbType.VarChar).Value = entry.Message;
private void button2_Click(object sender, EventArgs e)
{
try
{
string sSQL = "INSERT INTO StuTable (Name, Batch,CGPA, DOB, Program,
Picture)VALUES (#Name, #Batch,#CGPA,#DOB,#Program,#Picture)";
SqlCommand objCmd = new SqlCommand(sSQL, conn);
objCmd.Parameters.Add("#Name", SqlDbType.VarChar, 50);
objCmd.Parameters.Add("#Batch", SqlDbType.Int);
objCmd.Parameters.Add("#CGPA", SqlDbType.Float);
objCmd.Parameters.Add("#DOB", SqlDbType.VarChar, 50);
objCmd.Parameters.Add("#Program", SqlDbType.VarChar, 50);
objCmd.Parameters.Add("#Picture", SqlDbType.VarChar, 500);
//objCmd.Parameters["#RegdNo"].Value = Convert.ToInt32(textBox3.Text);
objCmd.Parameters["#Name"].Value = textBox4.Text;
objCmd.Parameters["#Batch"].Value = textBox5.Text;
objCmd.Parameters["#CGPA"].Value = textBox6.Text;
objCmd.Parameters["#DOB"].Value = maskedTextBox1.Text;
objCmd.Parameters["#Program"].Value = textBox8.Text;
objCmd.Parameters["#Picture"].Value = textBox9.Text;
objCmd.ExecuteNonQuery();
// MessageBox.Show("Record Added");
}
catch (Exception te)
{
MessageBox.Show(te.Message.ToString());
}
}

Insert record(s) DB from Form

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.

queries are not getting updated even on successful C# windows forms

private void button1_Click(object sender, EventArgs e)
{
SqlCeConnection connection = new SqlCeConnection(" Data Source=|DataDirectory|\\Database1.sdf; Persist Security Info=False ;");
connection.Open();
MessageBox.Show("Connection successful");
//listBox1.SelectedItem.ToString();
SqlCeCommand command = new SqlCeCommand("insert into malware (malwarename, threatlevel,malwaretype,kind,Description,Reg,network,developer,exportfix,date,id,signature)VALUES ('" + textBox1.Text + " ' , ' " + listBox1.SelectedItem + " ', '" + listBox2.SelectedItem + "' , '" + listBox3.SelectedItem + "', '" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox8.Text + "','" + dateTimePicker1.Value.Date.ToShortDateString() + "','" + textBox6.Text + "','" + textBox7.Text + "');", connection);
MessageBox.Show("fine till here ");
//SqlCeDataReader reader = command.ExecuteQuery();
//reader.Close();
int m = command.ExecuteNonQuery();
MessageBox.Show(m .ToString());
connection.Close();
}
Why my queries not updated on apply when I check?
Well, you didn't tell us do you have an error or not, here is the right way to do it.
First, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Second, you should dispose your connection with using keyword.
To ensure that connections are always closed, open the connection
inside of a using block, as shown in the following code fragment.
Doing so ensures that the connection is automatically closed when the
code exits the block.
Third, DATE could be reserved keyword in future releases of SQL Server. You might need to use it with square brackets like [DATE]. As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.
Here is an example;
private void button1_Click(object sender, EventArgs e)
{
using(SqlCeConnection connection = new SqlCeConnection("Data Source=|DataDirectory|\\Database1.sdf; Persist Security Info=False;"))
{
SqlCeCommand command = new SqlCeCommand("insert into malware (malwarename, threatlevel,malwaretype,kind,Description,Reg,network,developer,exportfix,[date],id,signature)
VALUES(#malwarename, #threatlevel, #malwaretype, #kind, #Description, #Reg, #network, #developer, #exportfix, #date, #id, #signature)",
connection);
command.Parameters.AddWithValue("#malwarename", textBox1.Text);
command.Parameters.AddWithValue("#threatlevel", listBox1.SelectedItem.ToString());
command.Parameters.AddWithValue("#malwaretype", listBox2.SelectedItem.ToString());
command.Parameters.AddWithValue("#kind", listBox3.SelectedItem.ToString());
command.Parameters.AddWithValue("#Descriptione", textBox2.Text);
command.Parameters.AddWithValue("#Reg", textBox3.Text);
command.Parameters.AddWithValue("#network", textBox4.Text);
command.Parameters.AddWithValue("#developer", textBox5.Text);
command.Parameters.AddWithValue("#exportfix", textBox8.Text);
command.Parameters.AddWithValue("#date", dateTimePicker1.Value.Date.ToShortDateString());
command.Parameters.AddWithValue("#id", textBox6.Text);
command.Parameters.AddWithValue(" #signature", textBox7.Text);
connection.Open();
int m = command.ExecuteNonQuery();
MessageBox.Show(m.ToString());
connection.Close();
}
}
Are you sure your checked database is your updated database ?
And then, Maybe you can put code statement of try-catch-finally ,check your app maybe throw some exception has occurred, try it!

Categories

Resources