【问题标题】:Cannot insert the data into the table using C# visual studio 2008无法使用 C# Visual Studio 2008 将数据插入表中
【发布时间】:2012-03-27 14:46:50
【问题描述】:

你好,我试图创建简单的学生表格 n 将数据添加到数据库中,但不能这样做,程序执行期间没有错误,应用程序执行良好但表中没有变化,n 值是nt 插入表中,请问问题可能是什么,我在下面写我的代码.. 提前谢谢:)

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);
        }
    }

【问题讨论】:

  • 你的一些参数有@而一些没有是有原因的吗?

标签: c# .net sql sql-server connection


【解决方案1】:

在查询的某些字段上添加括号[ ],因为其中一些是保留字:

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

[标题]

[图片]

更新 1

而不是SqlTransaction t = con.BeginTransaction();

试试这个:

SqlTransaction t = con.BeginTransaction(IsolationLevel.ReadCommitted)

Source: Use database transactions

【讨论】:

  • 没有解决方案兄弟我已经更正了我的代码,程序运行良好,但值未插入表中
  • 试过这个 SqlCommand cmd = new SqlCommand("INSERT INTO Student ([Title],[FirstName],[LastName],[FatherName],[Gender],[Class],[Section], [年龄],[出生日期],[宗教],[种姓],[图片],[地址],[家庭电话],[手机],[电子邮件]) 值(@Title,@FirstName,@LastName,@FatherName, @Gender,@Class,@Section,@Age,@DateOFBirth,@Religion,@Caste,@Image,@Address,@HomePhone,@CellPhone,@Email)",con);
  • 这个怎么样? SqlTransaction t = con.BeginTransaction(IsolationLevel.ReadCommitted)
  • 是的,尝试过,但我无法找到解决方案:((
【解决方案2】:

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

【讨论】:

  • 没有解决方案兄弟我已经更正了我的代码,程序运行良好,但值未插入表中
  • 转到 SQL Server Management Studio 并在您的数据库中执行: SELECT DB_ID() 针对此数据库 ID 运行分析器并查看服务器级别是否正在进行任何活动。
  • 我正在尝试使用 Visual Studio 内置提供的 sql server,我不使用管理工作室...
【解决方案3】:

1.) 不要传递这么多参数。你想添加一个学生,这应该会响起你所有的钟声。只传递一个参数 - 用你想要的值填充的学生类。

2.) 我认为这里不需要交易。你只想推送一个对象,所以如果它失败了,结果是一样的——没有做任何改变。

3.) 正如达伦所说,您的查询中没有正确编写参数

编辑: 刚刚尝试了简化版本,它就像一个魅力......这是代码:

页面.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();
            }
        }
    }

请尝试修改它以满足您的需求,如果它最终有效,请告诉我。它有一些问题(比如没有将学生类放在单独的文件中),但我希望你能明白。

【讨论】:

  • 是的,尝试使用较少的参数我也更正了查询,但结果相同:(,我必须从解决方案资源管理器手动将详细信息输入表中,它没有从表单中获取值,
  • @mujahid,您的函数是否返回任何错误或什么?你得到什么输出?您是否在表中提供所有强制值?
  • 函数 Addstudent() 返回整数值,我没有收到任何错误程序正在成功运行,但我无法看到插入到表中的值
  • @mujahid,好吧,这很奇怪...尝试逐行调试您的应用程序。这应该让我们知道出了什么问题。我敢打赌,有些东西是如此明显,以至于没有人检查它......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-26
相关资源
最近更新 更多