I have a Form that contains an "Add" button and a textBox, which is used to add information to a database table.
I need to check if the code entered in the TextBox is available before I can insert it.
My problem is that I get errors, as it attempts to add a "duplicate primary key" and I'm unsure of the source of error.
Below is the code I currently have:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection connection1 = new SqlConnection(connectionString);
connection1.Open();
String reqt1="select numero_cpte from compte where numero_cpte="+textBox1.Text+";";
SqlCommand sql1 = new SqlCommand(reqt1, connection1);
int d = int.Parse(textBox1.Text);
int dd = Convert.ToInt32(sql1.ExecuteScalar());
if(d == dd)
{
int o1 = sql1.ExecuteNonQuery();
MessageBox.Show("this account is not valide!!","Fiche ");
connection1.Close();
}
if (String.IsNullOrEmpty(textBox1.Text) == true)
{
MessageBox.Show("You should insert the code!!","Fiche",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand sql = new
SqlCommand("insert into compte values(" + textBox1.Text + ",'" +
textBox2.Text + "','" + type_cpteComboBox.SelectedItem.ToString() +
"','" + textBox2.Text + "','" + comboBox1.SelectedItem.ToString() +
"'," + comboBox2.SelectedItem.ToString() + ",'" +
checkBox1.Checked.ToString() + "','" + checkBox2.Checked.ToString() +
"','" +textBox5.Text+ "','" +textBox6.Text+ "');", connection);
int o = sql.ExecuteNonQuery();
MessageBox.Show(o + "Success of add","Fiche");
connection.Close();
textBox1.Text = "";
textBox2.Text = "";
}
This is the error I see:
The insert command works perfectly, but When I try to test if the code that I'am going to add in the base exists or not (by typing a code that I know exists), I get this exception.
It looks like your code drops down into the add code even if you have discovered that your number is a duplicate. Try adding "return;" after you close the connection.
MessageBox.Show("Ce compte existe.Veuillez sasir un numéro de compte valide!!", "Fiche Comptes");
connection1.Close();
return;
private object ExecuteScalar(string sql)
{
using (SqlConnection connection1 = new SqlConnection(connectionString))
{
connection1.Open();
SqlCommand sql1 = new SqlCommand(sql, connection1);
return sql1.ExecuteScalar();
}
}
The advantage of this is that you always know that your connection will be closed when you are done. Even if you are only going to be calling this method once, it improves readability and is therefore helpful.
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'm getting "System.InvalidOperationException: 'ExecuteNonQuery: Connection property has not been initialized.'" error while running the following code.
SqlConnection con = new SqlConnection(#"String_data");
public student_info()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
string insert = "INSERT INTO Table VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')";
SqlCommand cmd = new SqlCommand(insert);
cmd.ExecuteNonQuery();
MessageBox.Show("Data inserted successfully");
con.Close();
}
Please change the line. As you are only providing SQL Command and not providing connection i.e., server name, database name, user id and password.
SqlCommand cmd = new SqlCommand(insert);
To
SqlCommand cmd = new SqlCommand(con, insert);
You can learn here in SqlCommand Class
This question already has answers here:
Return value from SQL Server Insert command using c#
(3 answers)
Closed 8 years ago.
I have this code:
private void btnPotvrdi_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=BCKPSRVR;Initial Catalog=protokol;Integrated Security=True");
con.Open();
SqlCommand sc = new SqlCommand("insert into Knjiga (Datum_prijema, Predmet, Posiljalac, Adresa_posiljaoca, Primaoc, Datum_proslijeda) values ('" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "','" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + dateTimePicker2.Value.ToString("yyyy-MM-dd") + "');", con);
int o=sc.ExecuteNonQuery();
MessageBox.Show(o + " :Podaci su unešeni");
con.Close();
}
When I insert into this table, I have an auto_increment int primary key column called Osnovni_br. How can i get the last value of that column (Osnovni_br) in MessageBox or insted of MessageBox?
//read about sql injection here http://www.codeproject.com/Articles/11020/SQL-injection-attacks
using (var conn = new SqlCeConnection("Data Source=BCKPSRVR;Initial Catalog=protokol;Integrated Security=True"))
{
conn.Open();
using (var cmd = new SqlCeCommand())
{
cmd.Connection = conn;
cmd.CommandText = "insert into Knjiga (Datum_prijema, Predmet, Posiljalac, Adresa_posiljaoca, Primaoc, Datum_proslijeda) values (#Datum_prijema,#Predmet,#Posiljalac,#Adresa_posiljaoca,#Primaoc,#Datum_proslijeda);SELECT CAST(scope_identity() AS int)";
cmd.Parameters.AddWithValue("Datum_prijema", dateTimePicker1.Value.ToString("yyyy-MM-dd"));
//.... similarly add other values
int id = (int)cmd.ExecuteScalar();
}
}
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);
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!