C# winform 数据库操作知识点总结(干货)

时间:2022-09-24 19:22:17

1、数据库连接及操作

  在说数据库操作之前,先说一下数据库连接操作字符串的获取

  首先,点击服务器资源管理器,接下来选中数据连接右键点击添加连接,填入你要连接的服务器名称,点击单选框使用SQL Server 身份验证,填入用户名和密码,然后选择你要链接的数据库名称,点击测试连接,弹出连接成功,然后点击确定,此时,数据库已经连接成功。在服务器资源管理器下的数据连接下就可以看到你刚才链接的数据库,选中右键属性你就可以看见连接字符串

C# winform 数据库操作知识点总结(干货)C# winform 数据库操作知识点总结(干货)C# winform 数据库操作知识点总结(干货)

C# winform 数据库操作知识点总结(干货)C# winform 数据库操作知识点总结(干货)

C# winform 数据库操作知识点总结(干货)

  在获取到数据库连接字符串时,在App.config配置文件中可以写关于连接数据库的连接字符串,在这里配置好,在程序中直接通过代码调用连接字符串就行,直接上代码

   <connectionStrings>
<add name="connStr" connectionString="Data Source=(local);Initial Catalog=train;User ID=sa;Password=1234" />
<add name="train.Properties.Settings.trainConnectionString" connectionString="Data Source=(local);Initial Catalog=train;Persist Security Info=True;User ID=sa"
providerName="System.Data.SqlClient" />
</connectionStrings>

  在数据库连接时通过获取App.confi文件中的连接字符串连接数据库,代码如下

    /// <summary>
/// 数据库连接
/// </summary>
public class SqlConnect
{
/// <summary>
/// 连接字符串获取
/// </summary>
private static string connectString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; /// <summary>
/// 建立数据库连接
/// </summary>
/// <returns></returns>
public static SqlConnection getConn()
{
SqlConnection con = new SqlConnection(connectString); //Console.WriteLine("连接成功");
return con;
}
}

  

  接下来说一说数据库增删查改相关的操作

  通过c#操作数据库增加一条数据和java的思路逻辑差不多,只不过在在传值赋值的过程中采用的方式不一样,Java中sql语句用问号赋值传值,而c#是通过@加变量名传值,通过

AddWithValue方法赋值。是不是听得云里雾里的,给大家附上一段代码,就可以懂我说的

         /// <summary>
/// 插入站点
/// </summary>
/// <param name="stationName"></param>站点名称
/// <param name="stationEnName"></param>站点英文名
/// <param name="stationLng"></param>站点经度
/// <param name="stationLat"></param>站点纬度
/// <param name="stopTime"></param>停留时间
/// <param name="distance"></param>距离
/// <param name="lastStation"></param>上一站点名称
/// <param name="belongStation"></param>在本线路中的隶属站次
public void insertStation(String stationName, String stationEnName, double stationLng, double stationLat, int stopTime, double distance, String lastStation,int belongStation)
{
SqlConnection con = SqlConnect.getConn();
try
{
String InsertStr = "insert into WorkingLine (StationName,StationEnName,StationLng,StationLat,StationStopTime,StationDistance,LastStationName,SubjectStation) values (@STATIONNAME,@STATIONENNAME,@STATIONLNG,@STATIONLAT,@STATIONSTOPTIME,@STATIONDISTANCE,@LASTSTATIONNAME,@SUBJECTSTATION)";
SqlCommand command = con.CreateCommand();// 绑定SqlConnection对象
command.CommandText = InsertStr;
con.Open();
command.Parameters.AddWithValue("@STATIONNAME", stationName);
command.Parameters.AddWithValue("@STATIONENNAME", stationEnName); ;
command.Parameters.AddWithValue("@STATIONLNG", stationLng);
command.Parameters.AddWithValue("@STATIONLAT", stationLat);
command.Parameters.AddWithValue("@STATIONSTOPTIME", stopTime);
command.Parameters.AddWithValue("@STATIONDISTANCE", distance);
command.Parameters.AddWithValue("@LASTSTATIONNAME", lastStation);
command.Parameters.AddWithValue("@SUBJECTSTATION", belongStation);
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("添加站点失败");
}
finally
{
con.Close();
}
}

  删除,修改一条数据相对来说没有那么复杂,直接上代码

          /// <summary>
/// 删除站点
/// </summary>
/// <param name="name"></param>站点名称
public void deleteSta(String name) {
SqlConnection con = SqlConnect.getConn();
try
{
String deleteStr = "delete from WorkingLine where StationName=@STATIONNAME";
SqlCommand command = con.CreateCommand();// 绑定SqlConnection对象
command.CommandText = deleteStr;
con.Open();
command.Parameters.AddWithValue("@STATIONNAME", name);
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("删除站点失败");
}
finally
{
con.Close();
}
} /// <summary>
/// 修改某一站距上一站的距离
/// </summary>
/// <param name="stationname"></param>站名
/// <param name="distance"></param>距离
public void UpdateDistance(String stationname,double distance) {
SqlConnection con = SqlConnect.getConn();
try
{
String updateDisStr = "update WorkingLine set StationDistance =@DISTANCE where StationName =@STATIONNAME";
SqlCommand commmand = con.CreateCommand();// 绑定SqlConnection对象
commmand.CommandText = updateDisStr;
commmand.Parameters.AddWithValue("@DISTANCE", distance);
commmand.Parameters.AddWithValue("@STATIONNAME", stationname);
con.Open();
commmand.ExecuteNonQuery();//执行命令 }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("修改距离失败");
}
finally
{
con.Close();
}
}

  对于查询数据来说,我们普遍的操作就是用泛型List<E>来接收查询的数据,看代码就明白了

         /// <summary>
/// 查询列车运行线路信息,为DateGridView绑定数据源
/// </summary>
/// <returns></returns>
public List<DateView> SelectGridViewStation()
{
SqlDataReader reader = null;
DateView view = null;
List<DateView> list = new List<DateView>();
SqlConnection con = SqlConnect.getConn();
try
{
String selectGVStr = "select StationName,StationEnName,StationStopTime,StationLng,StationLat,StationDistance from WorkingLine order by SubjectStation asc";
SqlCommand command = con.CreateCommand();// 绑定SqlConnection对象
command.CommandText = selectGVStr;
con.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
view = new DateView()
{
StationName = reader.GetString(),
StationEnName = reader.GetString(),
stopTime=reader.GetInt32(),
lng=reader.GetDouble(),
lat = reader.GetDouble(),
distance=reader.GetDouble()
};
list.Add(view);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("查询线路信息失败");
}
finally
{
reader.Close();
con.Close();
}
return list;
}

  现在拿到数据了,我们怎么显示在对应的界面上呢!在winfrom窗体程序中,我习惯了用DataGridView控件,只需要为其绑定数据源就好了,我说的数据源是通过代码去实现的,请看

  SelectStation selSta = new SelectStation(); listDV = selSta.SelectGridViewStation(); dataGridView1.DataSource = listDV; 

2、DataGridView操作

  DataGridView控件默认选中第一行数据,如果不想让其选中,只需一步:dataGridView1.Rows[1].Selected = false;

  选取DataGridView控件中某一行某一列的值:dataGridView1.Rows[m ].Cells[n].Value.ToString();其中m,n分别表示行和列

C# winform 数据库操作知识点总结(干货)的更多相关文章

  1. WINFORM数据库操作&comma;有点像安装里面的SQLITE

    程序设计要求 设计一个用户管理系统,对系统中的用户进行管理.假定,用户表中有下列字段:用户名,密码,电话和 email 等信息.要求,1)利用 SQL server 首先创建用户数据表:2)实现对用户 ...

  2. C&num; winform 程序开发知识点总结(干货)

    1.数据库连接及操作 在说数据库操作之前,先说一下数据库连接操作字符串的获取 首先,点击服务器资源管理器,接下来选中数据连接右键点击添加连接,填入你要连接的服务器名称,点击单选框使用SQL Serve ...

  3. C&num;在winform中操作数据库,实现数据增删改查

    1.前言: 运行环境:VS2013+SQL2008+Windows10 程序界面预览: 使用的主要控件:dataGridview和menuStrip等. 2.功能具体介绍: 1.首先,我们要先实现基本 ...

  4. 学习MySQL之数据库操作(一)

    所有代码,均为自学时用到的测试与注释,知识细节或知识点不会面面俱到,亦不会有任何讲解,只做为自己学习复习用. ##数据库操作 ##创建数据库 myTest ,并将数据库字符集设为GBK CREATE ...

  5. 实验8 SQLite数据库操作

    实验报告 课程名称 实验8  SQLite数据库操作 实验日期 2016.5.6 实验项目名称 多媒体应用开发 实验地点 S30010 实验类型 □验证型    √设计型    □综合型 学  时 一 ...

  6. 我的Android六章&colon;Android中SQLite数据库操作

    今天学习的内容是Android中的SQLite数据库操作,在讲解这个内容之前小编在前面有一篇博客也是讲解了SQLite数据库的操作,而那篇博客的讲解是讲述了 如何在Window中通过DOM来操作数据库 ...

  7. 实验八 sqlite数据库操作

    实验报告 课程名称 基于Android平台移动互联网开发 实验日期 2016年5月3日 实验项目名称 SQLite数据库操作 实验地点 S30010 实验类型 □验证型    √设计型    □综合型 ...

  8. C&num; &period;NET更智能的数据库操作的封装

    前述: 对数据库操作的封装,相信网络上已经有一大堆,ORM框架,或者是.NET本身的EF,都很好的支持数据库操作.这篇文章是分享自己所思考的,对数据库操作的简单封装.我对于这篇文章,认为被浏览者所关注 ...

  9. Spring Boot&lpar;二&rpar;:数据库操作

    本文主要讲解如何通过spring boot来访问数据库,本文会演示三种方式来访问数据库,第一种是JdbcTemplate,第二种是JPA,第三种是Mybatis.之前已经提到过,本系列会以一个博客系统 ...

随机推荐

  1. Python MongoDB使用介绍

    MongoDB介绍 MongoDB是一个面向文档的,开源数据库程序,它平台无关.MongoDB像其他一些NoSQL数据库(但不是全部!)使用JSON结构的文档存储数据.这是使得数据非常灵活,不需要的S ...

  2. Oracle cmd 导出数据库或者表定义或者纯数据

    实例: expdp zypacs/Sfx371482@zyrisdb schemas=ZYPACS content=metadata_only CONTENT={ALL | DATA_ONLY | M ...

  3. jquery 使用方法&lpar;一&rpar;

    jquery是什麼? jquery,顾名思义,也就是JavaScript和查询(Query),即是辅助JavaScript开发的函數库. javascript是屬於網絡的腳本語言,宿主文件是html, ...

  4. 关于Task类

    private static void tt2() { Task task = null; ; i < ; i++) { task = Task.Factory.StartNew(callbac ...

  5. iptables基本操作

    一.基本操作 #启动防火墙 service iptables start #停止防火墙 service iptables stop #重启防火墙 service iptables restart #查 ...

  6. DataTable中的数据赋值给model z

    create table memberinfo ( member_id int, member_name varchar(20), member_birthday varchar(50) ) go / ...

  7. 卸载Visual Studio Code后删除右键Open with Code&hellip&semi;

    Win+R,输入  regedit  ,点击确认,进入注册表编辑器   Ctrl+F,搜索  Ticino  ,将搜索出来的Ticino都删除就行了

  8. salesforce零基础学习(八十三)analytics&colon;reportChart实现Dashboard&lpar;仪表盘&rpar;功能效果

    项目中经常会用到Report以及Dashboard来分析汇总数据,Dashboard可以指定view as user,如果针对不同的用户需要显示其允许查看的数据,比如  根据role hierarch ...

  9. Error Running Git Empty git --version output&colon;IDEA关联GitHub时出现这个错误

    刚刚学习使用idea中,想要把自己的项目上传到github,遇到这样一个问题,先记录下来,到时候解决了在把方法贴出来. ---------------------------------------- ...

  10. UOJ188 Sanrd Min&lowbar;25筛

    传送门 省选之前做数论题会不会有Debuff啊 这道题显然是要求\(1\)到\(x\)中所有数第二大质因子的大小之和,如果不存在第二大质因子就是\(0\) 线性筛似乎可以做,但是\(10^{11}\) ...