使用Windows Forms将图书馆应用程序连接到SQL Server
Windows窗体是用于制作应用程序的最佳工具之一。利用Windows窗体,你可以制作各种应用程序,从微型计算器到使用数据库的库应用程序。
据微软称,Windows窗体是一个用于构建Windows桌面应用程序的UI框架。
它提供了基于Visual Studio中提供的可视化设计器创建桌面应用程序的最有成效的方法之一。诸如可视化控件的拖放等功能使构建桌面应用程序变得容易。
在本教程中,我们将使用Windows窗体将一个库应用程序连接到一个SQL数据库服务器。我们将使用一个Windows窗体项目来添加新的窗体,编辑或删除库中的窗体。
我们还将管理数据库中的作者、商店和出版商,显示每个属性的信息,并在每次发生变化时刷新它。
前提条件
作为先决条件,读者必须具备以下条件。
- 对C#编程语言有基本了解。
- 对Windows窗体有基本的了解。
- 在你的系统上安装了Visual Studio。
- 在你的系统上安装了SQL Server。
安装指南
- 安装Visual Studio并设置工作环境。
- 安装SQL Server。
创建Pubs数据库
Pubs是一个数据库,被程序员用来作为学习工具,使用查询来获取数据。它包含大量关于书籍、作者、出版商和商店销售的信息。
首先,你应该在SQL服务器中创建Pubs数据库查询,这样它以后就可以连接到应用程序。
复制数据库查询后,把它粘贴为一个新的查询,并执行它。你应该能在屏幕的左边看到数据库的名称pubs 。

创建Pubs数据库
应用程序的主要形式
在本教程中,我们将使用Windows窗体建立一个端到端的应用程序,由图书管理员管理图书馆中的书籍。
我们将使用一个包含主表单的项目,我们还将添加其他3个表单,用于添加、编辑和删除数据库中的书籍。
打开项目后,我们将首先在主表单上工作。正如你所看到的,它有3个按钮,每个按钮用于不同的操作。

主窗体
添加一个刷新按钮和另外3个标签,在Titles 标签旁边,以便以后使用。同时,在DataGridView ,再添加4个列,以显示库的数据。
另外,别忘了把表格和按钮的颜色改成适合你口味的。
它应该看起来像这样。

带有其他标签的主表格
数据库连接
为了用C#连接到SQL服务器,我们将使用以下命令。
using System.Data.SqlClient;
下面的代码片断将连接你的计算机到数据库。但是,请注意,你需要把你自己的计算机名称而不是(HP-PAVILION)。
static SqlConnection connectionString = new SqlConnection(@"Data Source=HP-PAVILION;Initial Catalog=pubs;Integrated Security=True");
每个Select 查询将被写成string 。这些字符串在连接到SQL服务器时被转换为SQL查询。
public static DataTable dataAdapterSelect(string sqlQuery) {
// This method will convert any Select string to a query.
SqlDataAdapter DataAdapter = new SqlDataAdapter(sqlQuery, connectionString);
DataTable dt = new DataTable();
DataAdapter.Fill(dt);
return dt;
}
下面的方法将用来从数据库中Add,Edit, 和Delete 信息。
// This method will convert any string that would manipulate the data to a query.
public static void sqlCommandQueryReader(string sqlQuery) {
SqlCommand myCommand = new SqlCommand(sqlQuery, connectionString);
myCommand.Connection.Open();
SqlDataReader dr;
dr = myCommand.ExecuteReader();
while (dr.Read()) {
Console.WriteLine(dr[0]);
Console.WriteLine(dr[1]);
}
myCommand.Connection.Close();
}
下面的代码将使用dataAdapterSelect 方法将Select 字符串转换为SQL查询,并在datagridview 中显示。
// This query is responsible for displaying the information about the books on the DataGridView.
string sqlQuery = "SELECT title_id,title,type,pub_name,price,ytd_sales FROM titles inner join publishers ON titles.pub_id = publishers.pub_id";
DataTable dt = DataBaseConnection.dataAdapterSelect(sqlQuery);
foreach (DataRow dr in dt.Rows)
{
dataGridView1.Rows.Add(dr["title_id"], dr["pub_name"], dr["price"], dr["ytd_sales"], dr["title"],dr["type"]);
}
组件
添加表单
添加一本新书将需要titleID titleName titletype pubid pubbdate & 该书的price 。
我们将向用户请求上述信息,并使用sqlCommandQueryReader 方法将其插入到数据库中。

添加表格 - 从用户那里收集信息
// We will be using the sqlCommandQueryReader method to add a new book the database.
private void addButton_Click(object sender, EventArgs e) {
string titleID = titleIDTextBox.Text;
string titleName = titleNameTextBox.Text;
string titletype = Titletype.Text;
string pubid = pubbid.Text;
string pricee = price.Text;
string pubbdate = pubdate.Text;
string insertt = "insert into titles(title_id,title,type,pub_id,price,pubdate) values('" + titleID +
"','" + titleName + "','" + titletype + "','" + pubid + "','" + pricee + "','" + pubbdate + "');";
DataBaseConnection.sqlCommandQueryReader(insertt);
MessageBox.Show("Information inserted!");
}
编辑表格
编辑一本书需要当前的oldid 和该书的oldname ,以及该书的新Titlename,Titletype &Titleprice 。
我们将向用户索取信息,并使用sqlCommandQueryReader 方法在数据库中编辑它们。
.
编辑表格 - 在数据库中编辑信息
private void Edit_Click(object sender, EventArgs e) {
// We will be using the sqlCommandQueryReader method to edit an existing book from the database.
string Titlename = Tname.Text;
string Titletype = Ttype.Text;
string Titleprice = Tprice.Text;
string oid = oldid.Text;
string oname = oldname.Text;
if (Tname.Text.Length != 0 && Ttype.Text.Length != 0 &&
oldname.Text.Length != 0 && oldid.Text.Length != 0 && Tprice.Text.Length != 0) {
string editt = "update titles set title ='" + Titlename + "',type='" + Titletype + "',price='" + Titleprice + "'where titles.title_id ='" + oid + "' and titles.title='" + oname + "';";
DataBaseConnection.sqlCommandQueryReader(editt);
MessageBox.Show("Title has been edited!");
}
else
MessageBox.Show("Missing information!");
}
删除表格
删除一本书只需要使用titleid 功能。
我们将向用户请求id ,并使用sqlCommandQueryReader 方法从数据库中删除该书。

删除表格 - 从数据库中删除信息
private void Delbu_Click(object sender, EventArgs e) {
// We will be using the sqlCommandQueryReader method to delete an existing book from the database.
string dell = Del.Text;
string delete1 = "delete from roysched where roysched.title_id='"+dell+"'; delete from sales where sales.title_id='"+dell+"';delete from titles where titles.title_id='"+dell+"';";
if (Del.Text.Length != 0) {
DataBaseConnection.sqlCommandQueryReader(delete1);
MessageBox.Show("Title has been deleted!");
} else {
MessageBox.Show("enter a title id!");
}
}
刷新按钮
Refresh 按钮将显示数据库中的最新信息。当这个按钮被点击时,它将从数据库中获取最新的信息,并显示在这里。
private void refresh_Click(object sender, EventArgs e) {
// This query will show the data of the library on the DataGridview, and each time the user clicks the button, it will refresh the data.
dataGridView1.Rows.Clear();
string sqlQuery = "SELECT title_id,title,type,pub_name,price,ytd_sales FROM titles inner join publishers ON titles.pub_id = publishers.pub_id";
DataTable dt = DataBaseConnection.dataAdapterSelect(sqlQuery);
foreach (DataRow dr in dt.Rows) {
dataGridView1.Rows.Add(dr["title_id"], dr["pub_name"], dr["price"], dr["ytd_sales"], dr["title"], dr["type"]);
}
}
作者选项卡
作者标签将显示作者所写的每本书的au_id,au_fname,phone,address,city, 和count 。

作者选项卡 - 显示作者的相关信息
// This query will display all the information about the authors on the DataGridView.
string sqlQuery2 = "select * from authors order by au_fname asc";
DataTable dt2 = DataBaseConnection.dataAdapterSelect(sqlQuery2);
foreach (DataRow dr in dt2.Rows)
{
dataGridView2.Rows.Add(dr["au_id"], dr["au_fname"], dr["phone"], dr["address"], dr["city"]);
}
// This query will only display the count of the books that the author wrote on the DataGridView.
string sqlQuery3 = "SELECT authors.au_fname,count(titleauthor.title_id) as authorcount FROM authors, titleauthor WHERE authors.au_id = titleauthor.au_id GROUP BY authors.au_fname";
DataTable dt3 = DataBaseConnection.dataAdapterSelect(sqlQuery3);
foreach (DataRow dr in dt3.Rows)
{
dataGridView3.Rows.Add(dr["authorcount"]);
}
出版商选项卡
Publisher 选项卡将显示publishers 使用pub_id 的信息。

出版商选项卡 - 显示与出版商有关的信息
// This query will display all the information about the publishers on the DataGridView.
private void checkpub_Click(object sender, EventArgs e) {
string idd = puid.Text;
string sqlQuery00 = "select * from publishers where publishers.pub_id='" + idd + "'";
DataTable dt00 = DataBaseConnection.dataAdapterSelect(sqlQuery00);
if (dt00.Rows.Count > 0) {
foreach (DataRow dr in dt00.Rows) {
dataGridView4.Rows.Clear();
dataGridView4.Rows.Add(dr["pub_id"], dr["pub_name"], dr["city"], dr["state"], dr["country"]);
}
} else {
MessageBox.Show("This Id is does not exist!");
}
}
商店选项卡
Store 标签将显示使用left outer join 查询的折扣。

商店选项卡 - 显示有关商店和折扣的信息
// This query will display the discounts using the discount id & the store id.
string q5 = " select * from stores left outer join discounts on stores.stor_id = discounts.stor_id ";
DataTable q55 = DataBaseConnection.dataAdapterSelect(q5);
foreach (DataRow dr in q55.Rows) {
dataGridView5.Rows.Add(dr["stor_name"], dr["discount"]);
}
总结
在本教程中,我们已经学会了如何将一个应用程序连接到数据库,并将任何string 转换为一个SQL查询。我们还学习了如何从数据库中add,edit, 和delete 一本书,并显示书的作者、出版商和每个商店的折扣信息。
不要忘记测试一下代码,以充分了解它是如何工作的。