c# - 如何向数据库中插入数据? - 用户定义的类

标签 c# database visual-studio-2013 executenonquery

我正在试验数据库,并且正在寻找不同的方法来优化我的代码。在这里,我使用不同的类来停止重新编写相同的代码,例如添加、删除和更新我们使用相同的 ExecuteNonQuery() 方法。到目前为止,除了插入之外,更新删除方法运行良好。编译器不会给出任何错误,但从文本框中获取的值不会进入变量字符串查询。我是 c# 编码的新手。谁能帮我?或建议?

using DBconnectionExercise.DBConnection_Components;
namespace DBconnectionExercise
{
    public partial class Student_Form : Form
    {
        DBComps dc = new DBComps();

        //public string constring;
        //public SqlConnection con = null;
        //public SqlCommand com = null;
        public String query;

        public Student_Form()
        {
            InitializeComponent();

            //constring = "Data Source=ASHANE-PC\\ASHANESQL;Initial Catalog=SchoolDB;Integrated Security=True";
            //con = new SqlConnection(constring);

            dc.ConnectDB();


        }

        private void Form1_Load(object sender, EventArgs e)
        {

           loadGridData();

        }
        private void dtp_dob_ValueChanged(object sender, EventArgs e)
        {
            DateTime Now = DateTime.Today;
            DateTime Dob = dtp_dob.Value.Date;
            int a = Now.Year - Dob.Year;
            if (Now < Dob.AddYears(a)) a--;
            tb_Age.Text = a.ToString();
        }

        private void loadGridData()
        {
            try
            {
                query = "Select * from tb_Student";
                //dc.OpenCon();
                //SqlDataAdapter da = new SqlDataAdapter(query, con);
                DataTable dt1 = new DataTable();
                dt1 = dc.Data_Table(query);
                //da.Fill(dt);
                Stu_DataGrid.DataSource = dt1;
                //con.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void ClearData()
        {
            tb_Name.Clear();
            tb_Address.Clear();
            tb_Telno.Clear();
            tb_Search.Clear();
            tb_Age.Clear();
            dtp_dob.Value = DateTime.Today;

        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                String name = tb_Name.Text;
                DateTime dob = dtp_dob.Value.Date;
                int age = Convert.ToInt32(tb_Age.Text);
                String Address = tb_Address.Text;
                int telno = Convert.ToInt32(tb_Telno.Text);
                int line = 0;


                //con.Open();
                query = "Insert into tb_Student values(@Stu_Name, @Stu_DOB, @Age, @Stu_Address, @Stu_Tel_no)";
                //query = "Insert into tb_Student (Stu_Name, Stu_DOB, Age, Stu_Address, Stu_Tel_no) Values('" + name + "','" + dob + "','" + age + "','" + Address + "','" + telno + "')";
                MessageBox.Show(query);
                //com = new SqlCommand(query, con);

               // This is the Insert/save code

                DBComps.com.Parameters.AddWithValue("@Stu_Name", name);
                DBComps.com.Parameters.AddWithValue("@Stu_DOB", dob);
                DBComps.com.Parameters.AddWithValue("@Age", age);
                DBComps.com.Parameters.AddWithValue("@Stu_Address", Address);
                DBComps.com.Parameters.AddWithValue("@Stu_Tel_no", telno);

                //line = com.ExecuteNonQuery();
                line = dc.ExeNonQuery(query);
                //com.Dispose();
                //con.Close();

                if (line > 0)
                {
                    loadGridData();
                    ClearData();
                    MessageBox.Show("Data saved sucessfully!", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                    MessageBox.Show("Data not Saved", "Error Save", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

这是我用来编写 Sql 函数方法的 DBComps 类。

 namespace DBconnectionExercise.DBConnection_Components
    {
        public class DBComps
        {
            public String conSring;
            public SqlConnection con = null;
            public static SqlCommand com = null;

            public void ConnectDB()
            {
                conSring = "Data Source=ASHANE-PC\\ASHANESQL;Initial Catalog=SchoolDB;Integrated Security=True";
                con = new SqlConnection(conSring);
            }

            public void OpenCon()
            {
                con.Open();
            }

            public void CloseCon()
            {
                con.Close();
            }

            public int ExeNonQuery(String query) //the method for Insert, update and delete.
            {

                int line = 0;
                OpenCon();
                com = new SqlCommand(query, con);
                line = com.ExecuteNonQuery();
                com.Dispose();
                CloseCon();

                return line;
            }
    }
} 

最佳答案

这是与数据库对话的非常糟糕的方式,它可以使用 SQL 注入(inject)进行破解,并且由于您正在学习,现在是时候指出这一点了:

query = "Insert into tb_Student values('"+ name +"','"+ dob +"','"+ age +"','"+ Address +"','"+ telno +"')";

阅读有关 sql 注入(inject)的原因和方式,并寻找最佳实践以找到更好的方法。

关于c# - 如何向数据库中插入数据? - 用户定义的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30831312/

相关文章:

c# - 使用 VisualBrush 作为 OpacityMask

c++ - 访问冲突读取位置 0xCDCDCDD1

c# - ServiceStack.Redis 类型的客户端不保存值

c# - 如何在 C# 中通过表达式构建动态查询

c# - 字符串变量字符限制

database - 我应该使用哪个数据库服务器?

database - 在 REST API 中的何处存储资源 URI

database - 如何存储(和排序)模糊的日期范围?

asp.net - Visual Studio 项目恢复旧版本

visual-studio-2013 - 这个红色方形图标在 Visual Studio 2013 解决方案资源管理器中意味着什么?