namespace SQL_ServerApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataSet ds;
DataSet ds1;
SqlConnection Conn;
SqlDataAdapter sda;
SqlDataAdapter sda1;
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text == "")
{
// MessageBox.Show("请输入");
}
else
{
//尝试连接数据库
//创建数据库信息字符串
String connStr = "server=.;database="
// +textBox1.Text.Trim()
+ "Practise;uid=sa;pwd=123456";
Conn = new SqlConnection(connStr);
//打开
Conn.Open();
//判断数据库状态
if(Conn.State == ConnectionState.Open)
{
MessageBox.Show("连接");
}
//command对象,设置数据源,类型,文本
SqlCommand Comm = new SqlCommand();
Comm.Connection = Conn;
Comm.CommandType = CommandType.Text;
Comm.CommandText = "select * from Tab_1";
//执行查询方法获取数据ExecuteScalar()返回第一行第一列
//int i = Convert.ToInt32(Comm.ExecuteScalar());
// label1.Text = "共有" + i.ToString();
// Comm.CommandText = " update Tab_1 set 年龄 = 1 where 性别 ='女'";
// 更新,添加删除时 返回修改次数,
// label1.Text = "共有" + Comm.ExecuteNonQuery();
//ExecuteReader 返回包含数据的一个SqlDataReader数组列表对象
SqlDataReader sdr = Comm.ExecuteReader();
while (sdr.Read()) //读取数据
{
//sdr.HasRows返回布尔值 是否有数据;
listView1.Items.Add(sdr[0].ToString());
}
//一个Connection创建多个SqlDataReader 把第一个关了才能用第二个
sdr.Close();
//数据适配器 DataSet();
sda = new SqlDataAdapter();
//要填充的数据集
ds = new DataSet();
//绑定适配器的操作命令
sda.SelectCommand = Comm;
//填充数据集
sda.Fill(ds, "Tab_1");
sda.Fill(ds1, "Tab_2");
//添加到控件上显示
dataGridView1.DataSource = ds.Tables[0];
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
//关闭
// Conn.Close();
//关闭后清理所占资源,不能再次连接,需再次初始化后连接
// Conn.Dispose();
//判断数据库状态
//if (Conn.State == ConnectionState.Closed)
//{
// MessageBox.Show("关闭");
//}
//更新数据源;
DataTable dt = ds.Tables["Tab_1"];
//把表结构加载到 Tab_1
sda.FillSchema(dt, SchemaType.Mapped);
//找到被修改 的行
DataRow dr = dt.Rows.Find(textBox2.Text);
// 加载修改的数据给这一行
dr["性别"] = textBox3.Text;
// dr["年龄"] = textBox4.Text;
//帮助我们写Sql语句
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
// sda.Update()方法更新 需要一个修改的数据表
// sda.Update(dt);
//DataSet 合并数据内容 Merge()
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
textBox3.Text = dataGridView1.SelectedCells[0].Value.ToString();
// textBox2.Text = dataGridView1.SelectedRows[1].Cells.IndexOf(dataGridView1.Selec);
// textBox4.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox2.Text = "king";
}
}
}
VS C#【SQl Server 三】 数据库基本操作对象
猜你喜欢
转载自blog.csdn.net/qq_43886548/article/details/126711387
今日推荐
周排行