第一步,先建立与数据库的连接
第二步,在program.cs里面写程序
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaterDal
{
public static class SqliteHelper
{
//从配置文本中读取连接字符串
private static string connStr = "Data Source=数据库的名称;Initial Catalog=SWALL;User ID=SA;Password=666";//是这个数据库没错吧?
public static DataTable GetDataTable(string sql,params SqlParameter[] ps)
{
using (SqlConnection conn=new SqlConnection(connStr))
{
//构造适配器对象
SqlDataAdapter pter=new SqlDataAdapter(sql,conn);
//构造数据表,用于接收查询结果
DataTable dt=new DataTable();
//添加参数
pter.SelectCommand.Parameters.AddRange(ps);
//执行结果
pter.Fill(dt);
//返回结果集
return dt;
}
}
}
}
第三步,在项目里面写程序
private void button4_Click(object sender, EventArgs e)
{
DataTable Dt = SqliteHelper.GetDataTable("select * from jjjj");
dataGridView1.DataSource = Dt;
}
}
}
private void button4_Click(object sender, EventArgs e)
{
DataTable Dt = SqliteHelper.GetDataTable("select * from jjjj");
dataGridView1.DataSource = Dt;
}
}
}
private void button4_Click(object sender, EventArgs e)
{
DataTable Dt = SqliteHelper.GetDataTable("select * from lishiji");
dataGridView1.DataSource = Dt;
}
}
}
Form1.cs项目名
private void button4_Click(object sender, EventArgs e)
{
DataTable Dt = SqliteHelper.GetDataTable("select * from jjjj");
dataGridView1.DataSource = Dt;
}
}
}
FROM2.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.Windows.Forms;
using System.Data.OleDb;
using CaterDal;
namespace sqlssss
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataTable Dt = new DataTable();
Dt = SqliteHelper.GetDataTable("select * from lishiji");
DgvQueue.DataSource = Dt;
}
}
}
我写过连接access的,应该差不多,是先把数据库中的表显示到dataGridView控件上,然后从dataGridView中任意选择数据显示到文本框textbox中。你参考下吧:
(1)连接数据库——(可以写在一个按钮Click事件中)
OleDbConnection conn = new OleDbConnection();
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
connStr += @"Data\tlxs1.mdb";//我的数据库地址是在工程的debug文件夹Data文件夹里
conn.ConnectionString = connStr;//连接字符串
conn.Open();//打开连接
OleDbDataAdapter da = new OleDbDataAdapter(@"select * from renyuan", conn);//建立连接th1表,用于填充dataset
DataSet ds = new DataSet(); //创建DataSet对象,这里是datatable也可以
da.Fill(ds); //用OleDbDataAdapter对象da填充、更新刚创建的DataSet对象
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
(2)在dataGridView中提取数据显示到文本框中(放在显示按钮click事件中)
string[] str = new string[3];//
for (int i = 0; i < 3; i++)
{
str[i] = dataGridView1.CurrentRow.Cells[i ].Value.ToString();
shuju.AppendText(str[i]);//显示选择的行的数据
if (i == 11)
shuju.AppendText("\r\n");//每组数据换行显示
}
先写好连接数据库的语句,再对数据库进行操作!
大哥随便找本书看看吧