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!
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 have created a simple application every thing is working fine except update
portion insertion is working fine with same table data
My code is
private void button2_Click(object sender, EventArgs e)
{
string cmd = ("UPDATE submissionFee SET [stdName]='" + textBox2.Text + "', [fatherName]='" + textBox3.Text + "', [program]='" + textBox4.Text + "', [adress]='" + textBox5.Text + "',[email]='" + textBox6.Text + "', [cellNum]='" + textBox7.Text + "', [isPaid] = '" + textBox8.Text + "', [SubmissionDate] = '" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "'Where [ID]='" + textBox1.Text + "'");
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = cmd;
command.ExecuteNonQuery();
MessageBox.Show("Account Has Been Updated");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
MessageBox.Show("Please Enter Valid Data");
}
}
Error Screenshot
Probably the connection is already open when you try to open it.
Either:
1) Make sure you close the connection from the last time you used it.
2) Or, if it is sometimes supposed to be kept open, check if the connection is already open, and don't close it if it is. Something like:
bool bWasOpen = (connnection.State == ConnectionState.Open);
if (!bWasOpen)
connection.Open();
...
if (!bWasOpen)
connection.Close();
Much Worse than the crash: Your code is volunerable to Sql-injection.
--> Use parameterized sql.
The reason for this exception in the dialog is due to the connection state is already open; and hence it cannot be opened again. You must close the connection in your previous statement. Or, check if the connection closed, and then open it.
Some other tips to you is
Do not use Textbox1, Textbox2 etc., give them proper ID like txtStudentId, txtFatherName etc.,
User SQL Parameters to pass the values to your database. check the sample statements below
String query = "UPDATE submissionFee SET stdName=#stdName, fatherName=#fatherName where id=#id;";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id",txtID.txt); command.Parameters.Add("#stdName",txtStudent.Text); command.Parameters.Add("#fatherName",txtFatherName.Text);
command.ExecuteNonQuery();
Please use using statement when You query to database.
Why? Simple... it has implemented IDisposable.
P.S.
Use parameterized query to protect against SQL Injection attacks.
string insertStatement = UPDATE submissionFee SET stdName=#stdName,fatherName=#fatherName,program=#program,adress=#adress,email=#email,cellNum=#cellNum,isPaid=#isPaid,SubmissionDate=#SubmissionDate,ID=#ID
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(insertStatement, connection))
command.Parameters.AddWithValue("#ID",textBox1.Text);
command.Parameters.AddWithValue("#stdname",textbox2.Text);
command.Parameters.AddWithValue("#fathername",textBox3.Text);
command.Parameters.AddWithValue("#program",textBox4.Text);
command.Parameters.AddWithValue("#adress",textBox5.Text);
command.Parameters.AddWithValue("#email",textBox6.Text);
command.Parameters.AddWithValue("cellNum",textBox7.Text);
command.Parameters.AddWithValue("#isPaid",textBox8.Text);
command.Parameters.AddWithValue("#SubmissionDate",dateTimePicker1.Value.ToString("MM/dd/yyyy"));
connection.Open();
var results = command.ExecuteNonReader();
}
}
Part of code was taken from this link.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SAGAR\\SQLEXPRESS;Initial Catalog=ClinicDb;Integrated Security=True");
con.Open();
SqlCommand sc = new SqlCommand("insert into Patient_Details (Patient Id,Name,Age,Contact No,Address) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "',);", con);
object o= sc.ExecuteNonQuery();
MessageBox.Show(o +"Saved data");
con .Close();
}
I see a few things;
Patient Id should be [Patient Id] and Contact No should be [Contact No] since they are more than one word. As a best practice, change their names to one word.
You have extra , at the end of textBox5.Text + "', part.
But much more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
And use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
using(var con = new SqlConnection(connection))
using(var sc = con.CreateCommand())
{
sc.CommandText = #"insert into Patient_Details ([Patient Id],Name,Age,[Contact No],Address)
VALUES(#id, #name, #age, #no, #address)";
sc.Parameters.AddWithValue("#id", textBox1.Text);
sc.Parameters.AddWithValue("#name", textBox2.Text);
sc.Parameters.AddWithValue("#age", textBox3.Text);
sc.Parameters.AddWithValue("#no", textBox4.Text);
sc.Parameters.AddWithValue("#address", textBox5.Text);
con.Open();
int i = sc.ExecuteNonQuery();
MessageBox.Show(i + " Saved data");
}
By the way, I used AddWithValue in my example since you didn't tell us your column types but you don't. This method might generate surprising results sometimes. Use Add method overloads to specify your parameter type (SqlDbType) and it's size.
Getting an object from ExecuteNonQuery is really strange as well. It will return int as an effected rows count. It will be 1 or 0 in your case.
As a last thing, I strongly suspect your Patient Id, Age and Contact No columns should be some numeric type, not character typed.
fields and table names with spaces must be inside [], also you have 1 extra comma in the end of your query. Try:
SqlCommand sc = new SqlCommand("insert into [Patient_Details] ([Patient Id],Name,Age,[Contact No],Address) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "');", con);
object o= sc.ExecuteNonQuery();
also consider using parameters, since you are open to sql injection.
So I have this code to insert values from text-box into my database, but every time i execute my code and enters my data i get this message
"Syntax Error near keyword user"
string Connectionstring = #"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Bank_System.mdf;Integrated Security=True; User Instance=True";
SqlConnection cnn = new SqlConnection(Connectionstring);
cnn.Open();
SqlCommand cmd1 = new SqlCommand("insert into user values('" + int.Parse(textBox1.Text) + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + int.Parse(textBox6.Text) + "')", cnn);
SqlDataReader dr1 = cmd1.ExecuteReader();
dr1.Close();
MessageBox.Show(" Record inserted ", " information inserted");
cnn.Close();
USER is a reserved keyword in T-SQL. You should use it with square brackets like [USER]. However, the best solution is to change the name to a non-reserved word.
But more important, please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
By the way, I don't understand why you used ExecuteReader for an INSERT command. Looks like you just need to use ExecuteNonQuery instead.
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command.
Also use using statement to dispose your SqlConnection, SqlCommand.
using(SqlConnection cnn = new SqlConnection(Connectionstring))
using(SqlCommand cmd1 = cnn.CreateCommand())
{
cmd1.CommandText = "INSERT INTO [USER] VALUE(#p1, #p2, #p3, #p4, #p5, #p6)";
cmd1.Parameters.AddWithValue("#p1", int.Parse(textBox1.Text));
cmd1.Parameters.AddWithValue("#p2", textBox2.Text);
cmd1.Parameters.AddWithValue("#p3", textBox3.Text);
cmd1.Parameters.AddWithValue("#p4", textBox4.Text);
cmd1.Parameters.AddWithValue("#p5", textBox5.Text);
cmd1.Parameters.AddWithValue("#p6", int.Parse(textBox6.Text));
cnn.Open();
int count = cmd1.ExecuteNonQuery();
if(count > 0)
MessageBox.Show("Record inserted");
}
You try to concatenate int to string. The error is here: int.Parse(textBox1.Text) -> you need to convert to string after you test if is integer.
Try this for test : int.Parse(textBox1.Text).ToString() to see if this is your problem.
You try gather string to an integer by using:
"insert into user values('" + int.Parse(textBox1.Text) ....
=> string + int
Correct is:
SqlCommand cmd1 = new SqlCommand("insert into user values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "')", cnn);
try to validate if textBox1.Text and textBox6.Text before concatenate but is recommended to use parameters.
I am working on a Desktop application. I developed a form in which user enters data. When he clicks the submit button the data is saved in a database name PakReaEstat. The problem is the data is not inserted in the table and I get an error: SqlException was Unhandled.
When I click the Submit button it prompts error.
The code behind the button is as following:
protected void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo");
con.Open();
SqlCommand cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime)" +
"values (" + Convert.ToInt32(textBox1.Text) + ",'" +
textBox2.Text + "','" +
textBox4.Text + "'," +
textBox5.Text + "," +
textBox6.Text + "," +
textBox7.Text + "," +
textBox8.Text +
"," + textBox3.Text + ")", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Insertion successfully done");
}
Check you connection string and the SQL insert statement.
I recommend that you use sql parameters instead of the the textbox text property as value directly.
Beacause this is a common vulnerability, called SQL injection.
I also recommend to use using statement to ensure the connection is closed.
using (var con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo"))
{
con.Open();
using (var cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime)" + "values (#Application#,#LDAReg#, ... )", con))
{
cmd.Parameters.AddWithValue("#Application#", Convert.ToInt32(textBox1.Text));
cmd.Parameters.AddWithValue("#LDAReg#", textBox2.Text);
// add the other parameters ...
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Insertion successfully done");
There is problem in your SqlConnection
Make sure that your connection string is correct
SqlConnection con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo");
It should come like
SqlConnection con = new SqlConnection("Data Source=ADMIN3-PC;Initial Catalog=master;Integrated Security=True");
Always put your code in try... catch block if you are doing transaction with datatbase
If your connetion to databse is established and no issue there then
You are missing single quotes on last five textboxes. I suppose that last five columns are of type nvarchar in ur datatbse
change command to
SqlCommand cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime) values (" + Convert.ToInt32(textBox1.Text) + ",'" + textBox2.Text + "','" + textBox4.Text + " ','" + textBox5.Text + "','" + textBox6.Text+ "','" +textBox7.Text+ "','"+textBox8.Text +"','"+textBox3.Text+"')", con);