Data is not inserted in database table from windows form - c#

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

Related

How to back up SQL Server database via Winforms C#

I'm stuck on a issue where I need to backup my database via Winforms. I managed to find a sample SQL code in order to achieve this task.
My query here :
SqlConnection CON = new SqlConnection("Data Source=DBS\\DB;Initial Catalog=" + metroTextBox1.Text + ";Integrated Security=True");
Sql = "BACKUP DATABASE " + metroComboBox1.Text + " TO DISK = '" + metroTextBox4.Text + "\\" + metroComboBox1.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";
I have no idea how to proceed next. What should I use in this scenario? (ExecuteScalar, ExecuteNonQuery..etc)
Any help would be appreciated.
Note that Date time is also there in back up file name.
You define the SQL command to execute, and then instantiate a SqlCommand. Since the SQL statement isn't expected to return any data (a result set etc.), use ExecuteNonQuery:
string Sql = "BACKUP DATABASE " + metroComboBox1.Text + " TO DISK = '" + metroTextBox4.Text + "\\" + metroComboBox1.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";
using(SqlConnection CON = new SqlConnection("Data Source=DBS\\DB;Initial Catalog=" + metroTextBox1.Text + ";Integrated Security=True"))
using(SqlCommand cmdBackup = new SqlCommand(Sql, CON))
{
// open connection, execute command, close connection
CON.Open();
cmdBackup.ExecuteNonQuery();
CON.Close();
}
The general code:
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (var comm = conn.CreateCommand())
{
comm.CommandType = CommandType.Text;
comm.CommandText = "BACKUP DATABASE...";
comm.ExecuteNonQuery();
}
}

in this object o= sc.ExecuteNonQuery(); is giving me error sqlexceptionunhandled what to do suggest me a correct code

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.

exception of duplicate key in my code

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.

Syntax error near table_name

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.

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