我用visual studio创建了sql数据库,但是出现了一个错误,指出列名无效

时间:2016-03-28 09:56:09

标签: c# sqlexception

这是我的数据库:

CREATE TABLE [dbo].[std_info] (
[Enollment] INT          NOT NULL,
[Name]      VARCHAR (50) NULL,
[Addr]      VARCHAR (50) NULL,
[Phone]     VARCHAR (50) NULL,
[DOB]       VARCHAR (50) NULL,
[Email]     VARCHAR (50) NULL,
[Sem]       VARCHAR (50) NULL,
[Remark]    VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Enollment] ASC)
);

我已经使用sqlcommand

编写了将数据插入数据库的代码
                string sql="insert into std_info (Enrollment,Name,Addr,Phone,DOB,Email,Sem,Remark) values (@Enrollment,@Name,@Addr,@Phone,@DOB,@Email,@Sem,@Remark);";
                SqlCommand cmd = new SqlCommand(sql, sc);
                cmd.Parameters.AddWithValue("@Enrollment", int.Parse( txtenrol.Text));
                cmd.Parameters.AddWithValue("@Name", txtName.Text);
                cmd.Parameters.AddWithValue("@Addr", textadd.Text);
                cmd.Parameters.AddWithValue("@Phone", textphone.Text);
                cmd.Parameters.AddWithValue("@DOB", dateTimePicker1.Text);
                cmd.Parameters.AddWithValue("@Sem", cmbBatch.Text);
                cmd.Parameters.AddWithValue("@Email", textemail.Text);
                cmd.Parameters.AddWithValue("@Remark", textremark.Text);
                cmd.ExecuteNonQuery();`

请帮我解决问题。

2 个答案:

答案 0 :(得分:1)

最后删除分号;

string sql="insert into std_info (Enrollment,Name,Addr,Phone,DOB,Email,Sem,Remark) values (@Enrollment,@Name,@Addr,@Phone,@DOB,@Email,@Sem,@Remark)";

此外,由于Enrollment是主键,因此您无需显式提供其值。试试这个:

string sql="insert into std_info (Name,Addr,Phone,DOB,Email,Sem,Remark) values (@Name,@Addr,@Phone,@DOB,@Email,@Sem,@Remark)";
            SqlCommand cmd = new SqlCommand(sql, sc);
            cmd.Parameters.AddWithValue("@Name", txtName.Text);
            cmd.Parameters.AddWithValue("@Addr", textadd.Text);
            cmd.Parameters.AddWithValue("@Phone", textphone.Text);
            cmd.Parameters.AddWithValue("@DOB", dateTimePicker1.Text);
            cmd.Parameters.AddWithValue("@Sem", cmbBatch.Text);
            cmd.Parameters.AddWithValue("@Email", textemail.Text);
            cmd.Parameters.AddWithValue("@Remark", textremark.Text);
            cmd.ExecuteNonQuery();`

答案 1 :(得分:0)

CREATE TABLE [dbo]。[std_info]( [注册] INT NOT NULL,....