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");
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.
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'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);
}
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!
this is the code
public static void ChangeTable(string strSql, string FileName)
{
OleDbConnection c = MakeConnection(FileName);
OleDbCommand comm = new OleDbCommand();
comm.CommandText = strSql;
comm.Connection = c;
comm.ExecuteNonQuery();
c.Close();
}
strSql = "Insert into h3rot(name,lastname,tlfon,nyad,email,brodcuts)" +
" VALUES(
'
" +
TextBox1.Text +
"','" +
TextBox2.Text +
"'," +
phone +
"," +
pel +
",'" +
TextBox5.Text +
"','" +
DropDownList1.Text + "
')";
1) your code is SCREAMING out "sql injection" so you should REALLY be doing something to sanitize all of those textboxes. And you should at least be using parameter markers instead of just appending strings together.
2) you've probably exceeded the size of one of the columns in your database. without more information about what was in the textboxes or the schema of the database, there's not much else to say.
try DropDownList1.SelectedValue