62,046
社区成员
发帖
与我相关
我的任务
分享
private SqlDataAdapter adapter;
private DataSet dataSource;
string connectionString = "server=localhost; uid=sa; pwd=123; database=Courses";
string cmdString = "SELECT * FROM COURSE";
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(cmdString, sqlConnection);
sqlConnection.Open();
this.adapter = new SqlDataAdapter();
adapter.SelectCommand = sqlCmd;
this.dataSource = new DataSet();
adapter.Fill(dataSource, "COURSE");
int ret = this.adapter.Update(dataSource, "COURSE");
SqlConnection cn = new SqlConnection("server=localhost; uid=sa; pwd=123; database=Courses");
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM COURSE", cn);
DataTable dt = new DataTable();
da.Fill(dt);
//这里是增删改DataTable中的内容
//......
SqlCommandBuilder cb = new SqlCommandBuilder(da);
int result = da.Update(dt);
private void buttonSave_Click(object sender, EventArgs e)
{
// 如果是添加新记录
if (!this.isModify)
{
DataRow newRow = dataSource.Tables["COURSE"].NewRow();
newRow["课程号"] = this.textBoxCourseID.Text;
newRow["课程名"] = this.textBoxCourseName.Text;
newRow["任课教师"] = this.textBoxTeacher.Text;
dataSource.Tables["COURSE"].Rows.Add(newRow);
}
// 更新数据库
try
{
SqlCommandBuilder sb = new SqlCommandBuilder(this.adapter);
int ret = this.adapter.Update(dataSource, "COURSE");
if (ret != 0)
MessageBox.Show("数据保存成功!");
}
catch(Exception ex)
{
MessageBox.Show("数据保存失败!\r\n" + ex.Message);
}
this.SetState(true);
}