Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I have developed a form which has 3 fields(Name,USN and Sem). I have attached my code below. When I run this program I dont get any error and it works totally fine. Once the data has been inserted from UI, I get back and check in database table, and its empty. When I click on View button it shows the gridview of what all I have inserted at that instant of run. Not sure what is wrong. Please help.

^]

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace StudentEXE
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TRY"].ConnectionString);
            con.Open();
            SqlCommand query = new SqlCommand("insert into Student_Data values('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "')", con);
            query.ExecuteNonQuery();
            MessageBox.Show("Data Added Succesfully");
            con.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PopupWindos popup = new PopupWindos();
            popup.ShowDialog();
        }
    }
}


app.config file :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="TRY"
            connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>
Posted
Updated 1-Jun-15 23:56pm
v4

First off:
Understanding SQL Injection and Creating SQL Injection Proof ASP.NET Applications[^]

Never create queries from user input.

Have you met my Dad? His name is '; drop table *;'--
https://xkcd.com/327/[^]

C#
namespace StudentEXE
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            int rowsChanged = 0;
            using( SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TRY"].ConnectionString))
            {
            
            using(SqlCommand query = new SqlCommand("insert into Student_Data values(@param1,@param2,@param3)",con))
            {
            query.Parameters.AddRange({
             new SqlParameter("@param1",SqlDbType.Varchar){Value=textBox1.Text},
             new SqlParameter("@param2",SqlDbType.Varchar){Value=textBox2.Text},
             new SqlParameter("@param2",SqlDbType.Varchar){Value=textBox2.Text}
             });

            con.Open();
            //make sure something happened
            rowsChanged  = query.ExecuteNonQuery();
            con.Close();
            }
           }
           if(rowsChanged == 1)
             MessageBox.Show("Data Added Succesfully");
           if(rowsChanged == 0)
             MessageBox.Show("Didn't work");
           if(rowsChanged > 1)
             MessageBox.Show("Something went VERY wrong");
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            PopupWindos popup = new PopupWindos();
            popup.ShowDialog();
        }
    }
}


try that - see what you get.
 
Share this answer
 
Comments
partha143 21-May-15 14:08pm    
Still same problem. I am getting "Data Added Successfully" message and also when I click on view in the same instance of run(i.e without re-running the project), I am able to view the entries. But when i go to the datatable to view my entries manually, it is blank. Please help.
Andy Lanng 21-May-15 14:13pm    
Ok. If it says that it's saved, but it's not, then the transaction but be being rolled back. Are you aware of any transaction setting in your app?
partha143 21-May-15 14:20pm    
Sorry sir. I havent heard of it. Could you please provide me any link from which i can learn about it
Andy Lanng 21-May-15 14:43pm    
I'm on my phone atm so my abilities are somewhat reduced. Just google "sql transactions"
partha143 21-May-15 14:46pm    
Okay. Thank you for your help :)
It works fine for me.

Try using transactionscope instead:


C#
using System.Transactions;

...

public static void button1_Click()
{
    var options = new TransactionOptions
    {
        Timeout = TimeSpan.FromSeconds(120)
    };
    try
    {
        using (var scope = new TransactionScope(TransactionScopeOption.Required, options))
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TRY"].ConnectionString))
            {
                using (SqlCommand query = con.CreateCommand())
                {
                    query.CommandText = ("insert into wfe.Student_Data values(@param1,@param2,@param3)");
                    query.CommandType = CommandType.Text;
                    query.Parameters.Add("@param1", SqlDbType.VarChar).Value = "a";
                    query.Parameters.Add("@param2", SqlDbType.VarChar).Value = "b";
                    query.Parameters.Add("@param3", SqlDbType.VarChar).Value = "c";
                    con.Open();
                    var rowsadded = query.ExecuteNonQuery();
                    con.Close();
                    scope.Complete();

                    Console.WriteLine(@"{0} rows added",rowsadded);
                }
            }
        }
    }
    catch (Exception ec)
    {
        Console.WriteLine(ec);
    }
}


Note that you only need to open the connection at the last minute. The Using wrappers will help cleanly dispose of the connection even if an error does occur.

Note that I tested this in a console app so you will have to add your messageboxes back in
 
Share this answer
 
v2
Comments
partha143 2-Jun-15 5:09am    
Andy, Thanks a lot for your comments. I have resolved my issue. I just changed the connection string from my appconfig file to this :
add name="MyConnection" connectionstring="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\USERS\DOCUMENTS\VISUAL STUDIO 2010\PROJECTS\DATABASEPROJECT\DATABASEPROJECT\DATABASE.MDF;Integrated Security=True;User Instance=True" providername="System.Data.SqlClient">
Andy Lanng 2-Jun-15 5:15am    
hmhmmhahaha - it was the connection string?!? DOH.
Well the transactions are a good thing to learn and so it parameterized queries.

I'm really glad you sorted it.

Please post the new question as a new question. I'll look out for it ^_^
partha143 2-Jun-15 5:26am    
Thanks a lot Andy :). I am posting my new question now.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900