第一天看了看书本上的一些资源,第二天就动手试试看了 太基础了 大佬们轻点喷!(首先引入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]"];
}
}
}