简体   繁体   English

无法使用C#visual Studio 2008将数据插入表中

[英]Cannot insert the data into the table using C# visual studio 2008

hello every i was trying to create simple student form n add the data to the database but coudlnt do this, there was no error during the execution of the program, application executes nicely but no changes in the table, n the values are nt inserted into the table, what might b the problem plz suggest me, im writing my code below.. thanq in advance :) 你好,每当我尝试创建简单的学生表格n都将数据添加到数据库中,但要这样做时,程序执行过程中没有错误,应用程序执行得很好,但是表中没有任何更改,n值已插入nt桌子,问题可能会提示我什么,我在下面写我的代码.. thanq提前:)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace School.Project
{

class Student
{
    public static string constr = System.Configuration.ConfigurationManager.ConnectionStrings"SchoolConnectionString"].ConnectionString;

    public static int AddStudent(string title, string fname, string lname, string fathername, string gender, string clas, string sec, int age, string dob, string religion, string caste, string image, string address, string homeno, string cell, string email)
    {
        SqlConnection con = new SqlConnection(constr);
        con.Open();
        SqlTransaction t = con.BeginTransaction();

        SqlCommand cmd = new SqlCommand("INSERT INTO Student (Title,FirstName,LastName,FatherName,Gender,Class,Section,Age,DateOfBirth,Religion,Caste,Image,Address,HomePhone,CellPhone,Email) VALUES(@Title,@FirstName,@LastName,@FatherName,@Gender,@Class,@Section,@Age,@DateOFBirth,@Religion,@Caste,@Image,@Address,@HomePhone,@CellPhone,@Email)",con);
        cmd.Parameters.AddWithValue("@Title", title);
        cmd.Parameters.AddWithValue("FirstName", fname);
        cmd.Parameters.AddWithValue("LastName", lname);
        cmd.Parameters.AddWithValue("@FatherName", fathername);
        cmd.Parameters.AddWithValue("@Gender", gender);
        cmd.Parameters.AddWithValue("@Class", clas);
        cmd.Parameters.AddWithValue("@Section", sec);
        cmd.Parameters.AddWithValue("Age", age);
        cmd.Parameters.AddWithValue("DateOfBirth", dob);
        cmd.Parameters.AddWithValue("@Religion", religion);
        cmd.Parameters.AddWithValue("Caste", caste);
        cmd.Parameters.AddWithValue("Image", image);
        cmd.Parameters.AddWithValue("Address", address);
        cmd.Parameters.AddWithValue("@HomePhone", homeno);
        cmd.Parameters.AddWithValue("@CellPhone", cell);
        cmd.Parameters.AddWithValue("@Email", email);
        cmd.Transaction = t;

        int i = cmd.ExecuteNonQuery();
        t.Commit();
        con.Close();
        return i;
    }

    private void btSave_Click(object sender, EventArgs e)
    {
        string title = cbTitle.SelectedItem.ToString();
        string fname = txtfname.Text;
        string lname = txtlname.Text;
        string fathername = txtfatherName.Text;
        string gender = cbGender.SelectedItem.ToString();
        string clas = cbClass.SelectedItem.ToString();
        string section = cbSection.SelectedItem.ToString();
        int age = int.Parse(txtAge.Text);
        string dob = txtdob.Text;
        string religion = txtReligion.Text;
        string caste = txtCaste.Text;
        string imagepath = txtpath.Text;
        string address = txtAddress.Text;
        string homeno = txtHome.Text;
        string cell = txtCell.Text;
        string email = txtEMail.Text;

        int i = Project.Student.AddStudent(title, fname, lname, fathername, gender, clas, section, age, dob, religion, caste, imagepath, address, homeno, cell, email);
        if (i == 1)
        {
            MessageBox.Show("Student Added Succesfully, Thanq", "Inserted", MessageBoxButtons.OK, MessageBoxIcon.Information);
            ClearAll();
        }
        else
        {
            MessageBox.Show("Couldnt enter the data", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

add a bracket [ ] on some fields of your query because some of the are reserved words: 在查询的某些字段上添加方括号[ ] ,因为其中一些是保留字:

SqlCommand cmd = new SqlCommand("
INSERT INTO Student ([Title],FirstName,LastName,
                      FatherName,Gender,
                      [Class],Section,Age,DateOfBirth,
                      Religion,Caste,[Image],Address,
                      HomePhone,CellPhone,Email)             
VALUES(@Title,@FirstName,@LastName,
       @FatherName,@Gender,@Class,@Section,
       @Age,@DateOFBirth,@Religion,@Caste,
       @Image,@Address,@HomePhone,
       @CellPhone,@Email)",con);

[Title] [标题]

[Image] [图片]

UPDATED 1 更新1

Instead of SqlTransaction t = con.BeginTransaction(); 代替SqlTransaction t = con.BeginTransaction();

try this: 尝试这个:

SqlTransaction t = con.BeginTransaction(IsolationLevel.ReadCommitted)

Source: Use database transactions 来源:使用数据库事务

您的某些参数包含“ @”符号,而某些则不包含...。

1.) don't pass so many parameters. 1.)不要传递太多参数。 You want to add a STUDENT, that should ring all your bells. 您想添加一个学生,它应该让所有的铃声响起。 Pass only one parameter - class Student populated with the values you want. 仅传递一个参数-类Student填充所需的值。

2.) I don't think a transaction is necessary here. 2.)我认为这里不需要交易。 You want to push only one object, so if it fails, the result is the same - no changes done. 您只想推送一个对象,因此,如果失败,结果是相同的-没有更改。

3.) as Daren said, you don't have properly written parameters in your query 3.)正如达伦所说,您的查询中没有正确编写的参数

EDIT: Just tried the simplified version and it works like a charm... Here's the code: 编辑:刚刚尝试了简化的版本,它就像一个魅力...这是代码:

Page.aspx.cs Page.aspx.cs

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            btn.Click += new EventHandler(btn_Click);

        }

        void btn_Click(object sender, EventArgs e)
        {
            Student student = new Student() { Id = 1, Name = "John" };
            int rowsAffected = Student.AddStudent(student);

            Response.Write(rowsAffected);
        }
    }


    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public static int AddStudent(Student s)
        {
            string conString = System.Configuration.ConfigurationManager.ConnectionStrings["string1"].ConnectionString;

            using (SqlConnection con = new SqlConnection(conString))
            {
                con.Open();

                SqlCommand cmd = new SqlCommand("INSERT INTO Students (Name) VALUES (@Name)", con);
                cmd.Parameters.AddWithValue("@Name", s.Name);
                return cmd.ExecuteNonQuery();
            }
        }
    }

Please, try to modify it to suit your needs and let me know, if it finally works. 请尝试修改它以适合您的需求,如果最终可行,请告诉我。 It has some problems (like not putting the class Student in a separate file), but I hope you get the idea. 它有一些问题(例如不将Student类放在单独的文件中),但是我希望您能明白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM