第六周学习笔记
一、阅读器的使用
本周学习了阅读器的使用,先是调用SQL命令的方法ExecuteReader来执行命令,并获取数据阅读器。然后在数据阅读器的索引器中指定列名,从而访问当前记录的指定列的值。
C#部分主要代码如下:
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString =
"Server=(local);Database=HISDatabase;uid=sa;[email protected]";
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "SELECT * FROM tb_doctor WHERE [email protected];";//指定SQL命令的命令文本
sqlCommand.Parameters.AddWithValue("@no", "3150707048");//向SQL命令的参数集合添加参数的名称、值
sqlConnection.Open();
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
//调用SQL命令的方法ExecuteReader来执行命令,并获取数据阅读器
if (sqlDataReader.Read())
{
//在数据阅读器的索引器中指定列名,从而访问当前记录的指定列的值,并赋予相应控件
this.txb_no.Text = sqlDataReader["no"].ToString();
this.txb_name.Text = sqlDataReader["name"].ToString();
if (sqlDataReader["sex"].ToString ()== "True")
{
this.txb_gender.Text = "男";
}
else if (sqlDataReader["sex"].ToString() == "False")
{
this.txb_gender.Text = "女";
}
this.txb_birthdate.Text = ((DateTime)sqlDataReader["birthdate"]).ToShortDateString();
//生日首先转换为日期时间类型,再调用ToShortDateString方法获取日期部分
this.txb_post.Text = sqlDataReader["post"].ToString();
this.txb_department.Text = sqlDataReader["department"].ToString();
}
sqlDataReader.Close();//关闭数据阅读器(同时关闭连接)
优化如下:
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString =
"Server=(local);Database=HISDatabase;uid=sa;[email protected]";
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "SELECT * FROM tb_doctor WHERE [email protected];";
sqlCommand.Parameters.AddWithValue("@no", "3150707048");
sqlConnection.Open();
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
int
noOrdinal = sqlDataReader.GetOrdinal("no")
, nameOrdinal = sqlDataReader.GetOrdinal("name")
, genderOrdinal = sqlDataReader.GetOrdinal("sex")
, birthDateOrdinal = sqlDataReader.GetOrdinal("birthdate")
, classOrdinal = sqlDataReader.GetOrdinal("post")
, specialityOrdinal = sqlDataReader.GetOrdinal("department");
if (sqlDataReader.Read())
{
this.txb_no.Text = sqlDataReader["no"].ToString();
this.txb_name.Text = sqlDataReader["name"].ToString();
if (sqlDataReader["sex"].ToString() == "True")
{
this.txb_gender.Text = "男";
}
else if (sqlDataReader["sex"].ToString() == "False")
{
this.txb_gender.Text = "女";
}
this.txb_birthdate.Text = ((DateTime)sqlDataReader["birthdate"]).ToShortDateString();
this.txb_post.Text = sqlDataReader["post"].ToString();
this.txb_department.Text = sqlDataReader["department"].ToString();
}
sqlDataReader.Close();
运行结果如下:
要注意的是,在数据阅读器的索引器中指定列名时,原列名所在数据库中的数据类型进行相应的转化。
二、阅读器中日期控件、下拉框的使用
C#主要代码如下:
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString =
"Server=(local);Database=HISDatabase;uid=sa;[email protected]";
SqlCommand sqlCommand = new SqlCommand();
SqlCommand sqlCommand2 = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand2.Connection = sqlConnection;
sqlCommand.CommandText = "SELECT * FROM tb_doctor WHERE [email protected];";
sqlCommand2.CommandText = "SELECT * FROM tb_post;";
//指定SQL命令的命令文本;该命令查询所有职称,以用作下拉框数据源
sqlCommand.Parameters.AddWithValue("@no", "3150707048");
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
//声明并实例化SQL数据适配器,同时借助构造函数,将其SelectCommand属性设为先前创建的SQL命令
sqlDataAdapter.SelectCommand = sqlCommand2;//将SQL数据适配器的查询命令属性指向SQL命令
DataTable postTable = new DataTable();//声明并实例化数据表,用于保存所有职称,以用作下拉框数据源
sqlConnection.Open();
sqlDataAdapter.Fill(postTable);//SQL数据适配器读取数据,并填充职称数据表
this.cmb_post.DataSource = postTable;//将班级下拉框的数据源设为职称数据表
this.cmb_post.DisplayMember = "Name"; //将班级下拉框的显示成员设为职称数据表的名称列
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
if (sqlDataReader.Read())
{
this.txb_no.Text = sqlDataReader["no"].ToString();
this.txb_name.Text = sqlDataReader["name"].ToString();
this.rdb_1.Checked = (bool)sqlDataReader["sex"];
this.rdb_2.Checked = !(bool)sqlDataReader["sex"];
this.dtp_birthdate.Value = ((DateTime)sqlDataReader["birthdate"]);
this.cmb_post.SelectedText = (string )sqlDataReader["post"];
this.txb_department.Text = sqlDataReader["department"].ToString();
}
sqlDataReader.Close();
这节内容需要注意,下拉框的内容是另一张表里相应的内容,因此至少有两张表。需实例化两个SQL命令。
三、更新内容
载入后,如需对信息进行修改,点击更新按钮,修改信息,数据库端就更新了改信息。
主要代码如下:
SqlConnection sqlConnection = new SqlConnection();
//声明并实例化SQL连接;
sqlConnection.ConnectionString =
"Server=(local);Database=HISDatabase;uid=sa;[email protected]";
//在字符串变量中,描述连接字符串所需的服务器地址、数据库名称、集成安全性(即是否使用Windows验证);
SqlCommand sqlCommand = new SqlCommand(); //声明并实例化SQL命令;
sqlCommand.Connection = sqlConnection; //将SQL命令的连接属性指向SQL连接;
sqlCommand.CommandText = //指定SQL命令的命令文本;
"UPDATE tb_doctor"
+ " SET [email protected],[email protected],[email protected],[email protected],[email protected]"
+ " WHERE [email protected];";
sqlCommand.Parameters.AddWithValue("@name", this.txb_name.Text.Trim());
//向SQL命令的参数集合添加参数的名称、值;
sqlCommand.Parameters.AddWithValue("@sex", this.rdb_1.Checked);
sqlCommand.Parameters.AddWithValue("@birthdate", this.dtp_birthdate.Value);
sqlCommand.Parameters.AddWithValue("@post", (string )this.cmb_post.SelectedText);
sqlCommand.Parameters.AddWithValue("@department", this.txb_department.Text.Trim());
sqlCommand.Parameters.AddWithValue("@no", "3150707048");
sqlConnection.Open(); //打开SQL连接;
int rowAffected = sqlCommand.ExecuteNonQuery(); //调用SQL命令的方法ExecuteNonQuery来执行命令,向数据库写入数据,并返回受影响行数;
sqlConnection.Close(); //关闭SQL连接;
MessageBox.Show("更新" + rowAffected.ToString() + "行。");
四、实现打开图像功能
点击打开图片按钮,出现“打开图片”对话框,选择相应的图片,在PictureBox控件中显示出来。
主要代码如下:
public partial class frm_DoctorIM : Form
{
private string PhotoFileName;
public frm_DoctorIM()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterScreen;
this.cmb_post.DropDownStyle = ComboBoxStyle.DropDownList;
}
private void btn_Load_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString =
"Server=(local);Database=HISDatabase;uid=sa;[email protected]";
SqlCommand sqlCommand = new SqlCommand();
SqlCommand sqlCommand2 = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand2.Connection = sqlConnection;
sqlCommand.CommandText = "SELECT * FROM tb_doctor WHERE [email protected];";
sqlCommand2.CommandText = "SELECT * FROM tb_post;";
sqlCommand.Parameters.AddWithValue("@no", "3150707048");
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand2;
DataTable postTable = new DataTable();
sqlConnection.Open();
sqlDataAdapter.Fill(postTable);
this.cmb_post.DataSource = postTable;
this.cmb_post.DisplayMember = "Name";
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
byte[] photoBytes = null;
if (sqlDataReader.Read())
{
this.txb_no.Text = sqlDataReader["no"].ToString();
this.txb_name.Text = sqlDataReader["name"].ToString();
this.rdb_1.Checked = (bool)sqlDataReader["sex"];
this.rdb_2.Checked = !(bool)sqlDataReader["sex"];
this.dtp_birthdate.Value = ((DateTime)sqlDataReader["birthdate"]);
this.cmb_post.SelectedText = (string)sqlDataReader["post"];
this.txb_department.Text = sqlDataReader["department"].ToString();
photoBytes =
(sqlDataReader["Photo"] == DBNull.Value ? null : (byte[])sqlDataReader["Photo"]);
if (photoBytes != null)
//若学生的照片非空;
{
MemoryStream memoryStream = new MemoryStream(photoBytes);
//声明并实例化内存流,用于读取照片的字节数据;
this.ptb_Photo.Image = Image.FromStream(memoryStream);
//调用图像的静态方法FromStream从内存流中读取图像,并赋予图像框;
}
}
sqlDataReader.Close();
}
private void btn_Update_Click(object sender, EventArgs e)
{
MemoryStream memoryStream = new MemoryStream();
this.ptb_Photo.Image.Save(memoryStream, ImageFormat.Bmp);
byte[] photoBytes = new byte[memoryStream.Length];
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.Read(photoBytes, 0, photoBytes.Length);
SqlConnection sqlConnection = new SqlConnection();
//声明并实例化SQL连接;
sqlConnection.ConnectionString =
"Server=(local);Database=HISDatabase;uid=sa;[email protected]";
//在字符串变量中,描述连接字符串所需的服务器地址、数据库名称、集成安全性(即是否使用Windows验证);
SqlCommand sqlCommand = new SqlCommand(); //声明并实例化SQL命令;
sqlCommand.Connection = sqlConnection; //将SQL命令的连接属性指向SQL连接;
sqlCommand.CommandText = //指定SQL命令的命令文本;
"UPDATE tb_doctor"
+ " SET [email protected],[email protected],[email protected],[email protected],[email protected],[email protected]"
+ " WHERE [email protected];";
sqlCommand.Parameters.AddWithValue("@name", this.txb_name.Text.Trim());
//向SQL命令的参数集合添加参数的名称、值;
sqlCommand.Parameters.AddWithValue("@sex", this.rdb_1.Checked);
sqlCommand.Parameters.AddWithValue("@birthdate", this.dtp_birthdate.Value);
sqlCommand.Parameters.AddWithValue("@post", (string)this.cmb_post.SelectedText);
sqlCommand.Parameters.AddWithValue("@department", this.txb_department.Text.Trim());
sqlCommand.Parameters.AddWithValue("@Photo", photoBytes);
sqlCommand.Parameters.AddWithValue("@no", "3150707048");
sqlConnection.Open(); //打开SQL连接;
int rowAffected = sqlCommand.ExecuteNonQuery(); //调用SQL命令的方法ExecuteNonQuery来执行命令,向数据库写入数据,并返回受影响行数;
sqlConnection.Close(); //关闭SQL连接;
MessageBox.Show("更新" + rowAffected.ToString() + "行。");
}
private void btn_OpenPhoto_Click(object sender, EventArgs e)
{
OpenFileDialog openPhotoDialog = new OpenFileDialog()
{
Title = "打开照片文件(位图格式)"
,Filter = "BMP Files (*.bmp)|*.bmp;*.jpg;*.png;"
,InitialDirectory = @"C:\\"
};
if (openPhotoDialog.ShowDialog() == DialogResult.OK)
{
this.PhotoFileName = openPhotoDialog.FileName;
this.ptb_Photo.Image = Image.FromFile(this.PhotoFileName);
}
}
}
更新的内容如下即选中的行:
五、数据适配器和数据表的应用
利用数据网格视图来显示信息,实现载入,提交功能。数据库端数据也同步更新。
主要代码如下:
private void btn_Load_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString =
"Server=(local);Database=HISDatabase;uid=sa;[email protected]";
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "SELECT * FROM tb_doctor;";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
DataTable doctorTable = new DataTable();
sqlConnection.Open();
sqlDataAdapter.Fill(doctorTable);
sqlConnection.Close();
this.dgv_Score.DataSource = doctorTable;
}
private void btn_Submit_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString =
"Server=(local);Database=HISDatabase;uid=sa;[email protected]";
SqlCommand insertCommand = new SqlCommand();
insertCommand.Connection = sqlConnection;
insertCommand.CommandText =
"INSERT tb_doctor"
+ "(no,name,sex,post,department,phone,birthdate)"
+ " VALUES(@no,@name,@sex,@post,@department,,@phone,@birthdate);";
insertCommand.Parameters.Add("@no", SqlDbType.Char, 10, "no");
insertCommand.Parameters.Add("@name", SqlDbType.VarChar, 0, "name");
insertCommand.Parameters.Add("@sex", SqlDbType.VarChar, 0, "sex");
insertCommand.Parameters.Add("@post", SqlDbType.VarChar, 0, "post");
insertCommand.Parameters.Add("@department", SqlDbType.VarChar, 0, "department");
insertCommand.Parameters.Add("@phone", SqlDbType.VarChar, 0, "phone");
insertCommand.Parameters.Add("@birthdate", SqlDbType.VarChar, 0, "birthdate");
SqlCommand updateCommand = new SqlCommand();
updateCommand.Connection = sqlConnection;
updateCommand.CommandText =
"UPDATE tb_doctor"
+ " SET [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected]"
+ " WHERE [email protected];";
updateCommand.Parameters.Add("@NewNo", SqlDbType.Char, 10, "no");
updateCommand.Parameters.Add("@name", SqlDbType.VarChar, 0, "name");
updateCommand.Parameters.Add("@sex", SqlDbType.VarChar, 0, "sex");
updateCommand.Parameters.Add("@post", SqlDbType.VarChar, 0, "post");
updateCommand.Parameters.Add("@department", SqlDbType.VarChar, 0, "department");
updateCommand.Parameters.Add("@phone", SqlDbType.VarChar, 0, "phone");
updateCommand.Parameters.Add("@birthdate", SqlDbType.VarChar, 0, "birthdate");
updateCommand.Parameters.Add("@OldNo", SqlDbType.Char, 10, "no");
updateCommand.Parameters["@OldNo"].SourceVersion = DataRowVersion.Original;
SqlCommand deleteCommand = new SqlCommand(); //声明并实例化SQL命令;该命令用于删除;
deleteCommand.Connection = sqlConnection; //将SQL命令的连接属性指向SQL连接;
deleteCommand.CommandText = //指定SQL命令的命令文本;
"DELETE tb_doctor"
+ " WHERE [email protected];";
deleteCommand.Parameters.Add("@no", SqlDbType.Char, 10, "no");
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
//声明并实例化SQL数据适配器;
sqlDataAdapter.InsertCommand = insertCommand; //将SQL数据适配器的属性InsertCommand指向用于插入记录的SQL命令;
sqlDataAdapter.UpdateCommand = updateCommand; //将SQL数据适配器的属性UpdateCommand指向用于更新记录的SQL命令;
sqlDataAdapter.DeleteCommand = deleteCommand; //将SQL数据适配器的属性DeleteCommand指向用于删除记录的SQL命令;
DataTable doctorTable1 = (DataTable)this.dgv_Score.DataSource;
//声明数据表,并指向数据网格视图的数据源;数据源默认类型为object,还需强制转换类型;
sqlConnection.Open(); //打开SQL连接;
int rowAffected = sqlDataAdapter.Update(doctorTable1);
//SQL数据适配器根据学生数据表提交所有更新,并返回受影响行数;
sqlConnection.Close(); //关闭SQL连接;
MessageBox.Show("更新" + rowAffected.ToString() + "行。");
}