当前位置:网站首页>C#与数据库连接
C#与数据库连接
2022-06-23 16:22:00 【华不在意】
一、连接中使用到的组件
(1)一个按钮"Button"
(2)一个“DataGridView”(用于存放从数据库调来的表单)
二、连接代码
(1)form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;//头文件(要注意写上)
using System.Windows.Forms;
//Author dahua
//Data by 2022.6.23
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Btnconn_Click(object sender, EventArgs e)
{
//实例化对象
SqlConnection con = new SqlConnection();
//生成连接字符串
//string connectString = "Data Source=.\\LAPTOP-F8H1G1BE; database=Q;User ID=root;password=963456";
//读取配置文件
string connectString = System.Configuration.ConfigurationSettings.AppSettings["SQLconnectString"];
connectString=System.Configuration.ConfigurationManager.AppSettings["SQLconnectString"];
con.ConnectionString = connectString;
//建立连接
try
{
con.Open();
//提示是否连接成功
if (con.State == ConnectionState.Open)
{
MessageBox.Show("数据库连接成功!");
}
}
catch
{
MessageBox.Show("数据库连接失败!");
}
//创建对象
SqlCommand sqlcommand = new SqlCommand();
sqlcommand.Connection = con;
sqlcommand.CommandText = "select * from [dbo].[student]";
//执行Sql命令并将结果返回到接口IDataReader类型ider中
IDataReader idr = sqlcommand.ExecuteReader();
DataTable dt = new DataTable();
//将idr中数据填充到DataTable类型dt中
dt.Load(idr);
dataGridView1.DataSource = dt.DefaultView;
//关闭连接
idr.Close();
con.Close();
if (connectString != null)
{
con.Close();
}
}
}
}
(2) App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
//这里用到的是sql身份验证登陆(按需选择)
<add key="SQLconnectString1" value="Data Source=.\LAPTOP-F8H1G1BE; database=master;User ID=user1;password=;"/>
<add key="OrleconnectString" value="Data Source=.\LAPTOP-F8H1G1BE; database=Q;User ID=root;password=xxxxx"/>
//此处用到的是window身份验证登陆
<add key="SQLconnectString" value="server=.;database=master;integrated security=SSPI"/>
</appSettings>
</configuration>
三、运行结果
(1)数据库连接成功结果图
(2)数据库连接到表单的结果图
【注】使用App.config配置文件放置数据库连接的原因是
(1)方便将“.exe”文件打包发给用户后,用户在自己电脑 配置时,可以直接修改数据库的用户名和密码,就可直接使用该文件。
(2)有时需要连接多个数据库,将数据库的连接放在配置文件中,方便后期统一管理或修改。
边栏推荐
- Implementation of network data transmission by golang Gob
- Jetpack compose and material you FAQs
- stylegan2:analyzing and improving the image quality of stylegan
- Zhongda face sketch FERET database (cufsf)
- What does websocket do?
- Apache基金会正式宣布Apache InLong成为顶级项目
- 元宇宙带来的社会结构和资本制度演变
- Medical image segmentation website
- 科大讯飞神经影像疾病预测方案!
- Shushulang passed the listing hearing: the gross profit margin of the tablet business fell, and the profit in 2021 fell by 11% year-on-year
猜你喜欢

The Google play academy team PK competition is in full swing!

Thinking analysis of binary search method

Tensorrt Paser loading onnx inference use

Identify and stop the process that's listening on port 8080 or configure this application

Apache foundation officially announced Apache inlong as a top-level project

Golang writes to JSON files

stylegan2:analyzing and improving the image quality of stylegan

Coatnet: marrying revolution and attention for all data sizes
![Leetcode: interview question 08.13 Stacking bin [top-down DFS + memory or bottom-up sorting + DP]](/img/22/220e802da7543c2b14b7057e4458b7.png)
Leetcode: interview question 08.13 Stacking bin [top-down DFS + memory or bottom-up sorting + DP]

走好数据中台最后一公里,为什么说数据服务 API 是数据中台的标配?
随机推荐
leetcode:30. 串联所有单词的子串【Counter匹配 + 剪枝】
Safe and comfortable, a new generation of Qijun carefully interprets the love of the old father
Solution: in the verification phase, the first batch does not report errors, and the second batch reports CUDA exceeded errors
[untitled] Application of laser welding in medical treatment
Coatnet: marrying revolution and attention for all data sizes
如何选择示波器?这10点一定要考虑!
Interface ownership dispute
Date转换为LocalDateTime
读书郎通过上市聆讯:平板业务毛利率走低,2021年利润同比下滑11%
走好数据中台最后一公里,为什么说数据服务 API 是数据中台的标配?
接口的所有权之争
ADC数字地DGND、模拟地AGND的谜团!
I successfully joined the company with 27K ByteDance. This interview notes on software testing has benefited me for life
Golang write file code example
短视频平台开发,点击输入框时自动弹出软键盘
聚焦:ZK-SNARK 技术
ASEMI快恢复二极管RS1M、US1M和US1G能相互代换吗
Now I want to buy stocks. How do I open an account? Is it safe to open a mobile account?
Medical image segmentation website
Importance and purpose of test