第一天看了看书本上的一些资源,第二天就动手试试看了 太基础了 大佬们轻点喷!(首先引入using System.Data.SqlClient;)
1.首先是配置数据库连接 代码放下面 我用的是本机电脑里的数据库所以就选用了集成的方式,别的方式不会的可以网上查一下
代码如下:
string connstring = "integrated security = SSPI;database=doul; ";
2.第二步是写sql语句 用来执行对数据库的操作
string sqlstring = “select * from Customers”;
3 .第三步是调用 SqlClient; (具体属性可以查下 本人60多岁打字速度有限 这里就不一一介绍了!咳咳)
SqlConnection con = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand(sqlstring, con);
SqlDataAdapter dr = new SqlDataAdapter(sqlstring, con);
DataSet ds = new DataSet();
dr.Fill(ds, "[Customers]");
4.把操作结果用控件dataGridView来体现出来
dataGridView1.DataSource = ds.Tables["[Customers]"];
整体代码和页面如下:
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.Windows.Forms;
using System.Data.SqlClient;
namespace _8._18
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connstring = "integrated security = SSPI;database=doul; ";
string sqlstring = "select * from Customers";
SqlConnection con = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand(sqlstring, con);
SqlDataAdapter dr = new SqlDataAdapter(sqlstring, con);
DataSet ds = new DataSet();
dr.Fill(ds, "[Customers]");
dataGridView1.DataSource = ds.Tables["[Customers]"];
}
private void button2_Click(object sender, EventArgs e)
{
string connstring = "integrated security = SSPI;database=doul; ";
string sqlstring = "insert into Customers(CompanyName,ContactName,Address,Phone)values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"') ";
SqlConnection con = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand(sqlstring, con);
SqlDataAdapter dr = new SqlDataAdapter(sqlstring, con);
DataSet ds = new DataSet();
dr.Fill(ds, "[Customers]");
dataGridView1.DataSource = ds.Tables["[Customers]"];
}
}
}

该博客介绍了一个简单的C#应用程序,用于连接到本地SQL Server数据库并执行查询。首先配置了集成安全性的数据库连接字符串,然后编写SQL语句从`Customers`表中选择所有记录。接着使用SqlClient库创建数据库连接、命令和适配器,并填充数据集。最后,将结果显示在dataGridView控件上。此外,还展示了如何插入新记录到`Customers`表。
&spm=1001.2101.3001.5002&articleId=121624870&d=1&t=3&u=02adb5b7cc30490f80d0f2c87af0df43)
2632

被折叠的 条评论
为什么被折叠?



