数据未保存到数据库中 [英] Data not saving into database

查看:83
本文介绍了数据未保存到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个包含3个字段(Name,USN和Sem)的表单。我在下面附上了我的代码。当我运行这个程序时,我没有得到任何错误,它完全正常。从UI插入数据后,我回来检查数据库表,并将其清空。当我单击查看按钮时,它会显示我在运行的那一刻所插入的内容的网格视图。不确定有什么问题。请帮忙。



^ ]



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.

^]

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文件:



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>

推荐答案

首先关闭:

了解SQL注入和创建SQL注入证明ASP.NET应用程序 [ ^ ]



永远不要根据用户输入创建查询。



你见过爸爸了吗?他的名字是 '; drop table *;' -

https://xkcd.com/327/ [ ^ ]



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/[^]

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.


对我来说很好。



尝试使用transactionscope:





It works fine for me.

Try using transactionscope instead:


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


这篇关于数据未保存到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆