【发布时间】:2021-08-16 09:30:22
【问题描述】:
我有一个这样的 SQL Server 表:
create table LectureNotice
(
NoticeId int identity(1,1),
NoticeTitle varchar(50),
NoticeContent varchar(1000),
CreatedDate varchar(20),
LecturerId int,
CreatedBy varchar(50),
CourseId int,
NoticeViewNumber int
);
我想使用以下查询将数据插入表中
private void btnCrudInsert_Click(object sender, EventArgs e)
{
string query = @"insert into LectureNotice values(@NoticeId, @NoticeTitle, @NoticeContent, @CreatedDate, @LecturerId,
@CreatedBy, @CourseId)";
using (SqlConnection connection = new SqlConnection(Helper.ConnectionHelper("KLAS_DB")))
{
try
{
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.AddWithValue("@NoticeId", noticeId);
cmd.Parameters.AddWithValue("@NoticeTitle", txtTitle.Text.Trim());
cmd.Parameters.AddWithValue("@NoticeContent", txtContent.Text.Trim());
cmd.Parameters.AddWithValue("@CreatedDate", txtCreatedDate.Text.ToString().Trim());
cmd.Parameters.AddWithValue("@LecturerId", int.Parse(txtLecturerId.Text.Trim()));
cmd.Parameters.AddWithValue("@CreatedBy", txtLecturer.Text.Trim());
cmd.Parameters.AddWithValue("@CourseId", int.Parse(txtCourseId.Text));
cmd.ExecuteNonQuery();
}
catch (Exception ex) {
MessageBox.Show("btnCrudInsert" + ex.Message);
}
connection.Close();
}
}
当我执行查询时,发生了一些错误。如下:
-
我尝试在文本框中插入
2021-05-28,然后错误显示为failed when converting nvarchar value to type int。即使在 SQL Server 表中,我也将createdDate定义为varchar。 -
在
CreatedBy列中,当我将值插入时,错误还显示failed when converting nvarchar value to type int。
- 最终错误出现在
NoticeContent中,我设置了varchar(max),但是当我通过text box将值插入其中时,错误显示为binary or string value would be truncated。
我的LectureNotice 表是从其他 2 个表继承而来的好处是
create table Course
(
CourseId int,
CourseName varchar(50),
CourseType varchar(50),
CourseCredit int,
Enrollment int,
primary key(CourseId)
);
create table Lecturer
(
Id int,
FirstName varchar(50),
LastName varchar(50),
Email varchar(50),
PhoneNumber varchar(13),
Department varchar(50),
LecturerType varchar(50),
primary key(Id)
);
还有一些过滤器,例如
alter table LectureNotice
add constraint FK_Lnotice_CourseId
foreign key(CourseId) references Course(CourseId)
on update cascade
on delete set null;
go
alter table LectureNotice
add constraint FK_Lnotice_LecturerId
foreign key(LecturerId) references Lecturer(Id)
on update cascade
on delete set null;
go
我已尝试并查找其他解决方案,但没有一个与我相同。
【问题讨论】:
标签: c# sql-server winforms