简体   繁体   中英

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

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

Instead of SqlTransaction t = con.BeginTransaction();

try this:

SqlTransaction t = con.BeginTransaction(IsolationLevel.ReadCommitted)

Source: Use database transactions

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

1.) don't pass so many parameters. You want to add a STUDENT, that should ring all your bells. Pass only one parameter - class Student populated with the values you want.

2.) I don't think a transaction is necessary here. 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

EDIT: Just tried the simplified version and it works like a charm... Here's the code:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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