if (textBox5.Text.Trim() == string.Empty || textBox4.Text.Trim() == string.Empty)
{
MessageBox.Show("請輸入課程號和課程名!");
}
else {
string consqlserver = "server = .;Initial Catalog=Students;integrated security=true";
SqlConnection conn = new SqlConnection(consqlserver);
string sql = "insert into 課程(課程號,課程名) values('" + textBox5.Text.Trim() + "','" + textBox4.Text.Trim() + "')";
conn.Open();
string sql1 = "select * from 課程 where 課程名 ='" + textBox4.Text + "' or 課程號 ='" + textBox5.Text + "'";
string sql2 = "update 課程 set " +
" 課程號 = '" + textBox5.Text + "'," +
" 課程名 = '" + textBox4.Text + "', where 課程名 = '" + textBox4.Text + "' or 課程號 = '" + textBox5.Text + "'";
SqlCommand mysqlcommand = conn.CreateCommand();
mysqlcommand.CommandText = sql;
SqlDataReader myread = mysqlcommand.ExecuteReader();
if (myread.HasRows)
{
DialogResult result = MessageBox.Show("已存在課程,是否在原有信息上面更新信息?","Attention!",MessageBoxButtons.OKCancel, MessageBoxIcon.Information,MessageBoxDefaultButton.Button3);
switch (result)
{
case DialogResult.OK:
conn.Close();
conn.Open();
mysqlcommand.CommandText = sql2;
mysqlcommand.ExecuteNonQuery();
conn.Close();
MessageBox.Show("已完成課程的更新!");
break;
case DialogResult.Cancel:
MessageBox.Show("未做任何修改!");
break;
}
}
else
{
conn.Close();
conn.Open();
mysqlcommand.CommandText = sql;
mysqlcommand.ExecuteNonQuery();
conn.Close();
MessageBox.Show("添加該新課程成功!");
}
}
this.Hide();
Frmindex frmindex = new Frmindex();
frmindex.ShowDialog();
}
http://www.cnblogs.com/rainman/archive/2012/03/13/2393975.html