C#操作SQL数据库

C#操作SQL数据库

本篇文章主要讲解一下使用C#语言来对SQL数据库进行【添加数据】【查询数据】【删除数据】【更新数据】相关操作


01

创建连接对象


1)引用命名空间

 using System.Data.SqlClient;

2)连接创建的数据库,在程序加载的时候进行连接

//存放数据库数据源

string strMyConnectoion = "Data Source=DESKTOP-U6V69B6;Initial Catalog=2022_Karl;Integrated Security=True";

SqlConnection myConnection;//数据库连接对象

private void Form1_Load(object sender, EventArgs e)

{

//创建数据库连接对象

myConnection = new SqlConnection(strMyConnectoion);

}


02

数据写入


在相应的输入栏里输入数据,点击【添加数据】即可将数据添加到表内

C#操作SQL数据库


以下为源代码:

private void btnAdd_Click(object sender, EventArgs e)

{

bool res = false;

try

{

//打开数据库

myConnection.Open();

//实例化命令对象

SqlCommand myCommand = new SqlCommand();

//把要操作的数据库传过来

myCommand.Connection = myConnection;

//操作类型为文本类型

myCommand.CommandType = CommandType.Text;

//

myCommand.CommandText = @"insert into studentList(学号,姓名,年龄,性别,地址) values(@学号,@姓名,@年龄,@性别,@地址)";

myCommand.Parameters.Add (new SqlParameter("@学号", textBox_ID.Text));

myCommand.Parameters.Add (new SqlParameter("@姓名", textBox_Name.Text));

myCommand.Parameters.Add (new SqlParameter("@年龄", textBox_Age.Text));

myCommand.Parameters.Add (new SqlParameter("@性别", textBox_Sex.Text));

myCommand.Parameters.Add (new SqlParameter("@地址", textBox_Addr.Text));

//提交数据

myCommand.ExecuteNonQuery();

//关闭数据库

myConnection.Close();

res = true;

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

myConnection.Close();

}

 

if (res)

{

MessageBox.Show("添加成功");

}

}


03

数据查询


点击【查询数据】,可以看到表内数据被成功显示出来了

C#操作SQL数据库


以下为源代码:

private void btnFind_Click(object sender, EventArgs e)

{

//select * from 表名 查询整个表

//select 条件 from 表名 按条件查询表格

try

{

//打开数据库

myConnection.Open();

//实例化命令对象

SqlCommand myCommand = new SqlCommand();

//把要操作的数据库传过来

myCommand.Connection = myConnection;

//操作类型为文本类型

myCommand.CommandType = CommandType.Text;

//命令格式,代表查询全部

myCommand.CommandText = @"select * from studentList";

//创建DataAdapter对象

SqlDataAdapter sda = new SqlDataAdapter(myCommand);

//创建DataSet对象

DataSet ds = new DataSet();

//将studentList这张表填充到DataSet数据集中

sda.Fill(ds, "studentList");

//将studentList这张表显示到控件上

dataGridView1.DataSource = ds.Tables["studentList"].DefaultView;

//关闭数据库

myConnection.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

myConnection.Close();

}

}


04

按条件查询


在按姓名查询栏输入karl,点击【按姓名查询】可以看到符合条件的数据被筛选出来了

C#操作SQL数据库


以下为源代码:

private void btnCdtFind_Click(object sender, EventArgs e)

{

//select * from 表名 -查询整个表

//select 列名 from 表名 where 列 运算符 值 -按条件查询表格

try

{

//打开数据库

myConnection.Open();

//实例化命令对象

SqlCommand myCommand = new SqlCommand();

//把要操作的数据库传过来

myCommand.Connection = myConnection;

//操作类型为文本类型

myCommand.CommandType = CommandType.Text;

//命令格式,代表按姓名查询

myCommand.CommandText = @"select * from studentList where 姓名 =@姓名";

 

myCommand.Parameters.Add(new SqlParameter("@姓名", textBox_Cdt.Text));

//开始查询

int res =Convert.ToInt32(myCommand.ExecuteScalar());

//如果查询不到,报错

if (res == 0)

{

throw new Exception("查无此人");

}

//创建DataAdapter对象

SqlDataAdapter sda = new SqlDataAdapter(myCommand);

//创建DataSet对象

DataSet ds = new DataSet();

//将studentList这张表填充到DataSet数据集中

sda.Fill(ds, "studentList");

//将studentList这张表显示到控件上

dataGridView1.DataSource = ds.Tables["studentList"].DefaultView;

//关闭数据库

myConnection.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

myConnection.Close();

}

}


05

删除数据


1)点击【查询数据】查看表内数据

C#操作SQL数据库


2)在按姓名删除栏输入karl,点击【按姓名删除】在弹出的窗口点击【确定】

C#操作SQL数据库


3)再次点击【查询数据】可以发现姓名为karl的数据已经被删除了

C#操作SQL数据库


以下为源代码:

private void btn_Del_Click(object sender, EventArgs e)

{

//删除语法

//delete from 表名 where 条件

try

{

//打开数据库

myConnection.Open();

//实例化命令对象

SqlCommand myCommand = new SqlCommand();

//把要操作的数据库传过来

myCommand.Connection = myConnection;

//操作类型为文本类型

myCommand.CommandType = CommandType.Text;

//命令格式,代表按姓名查询

myCommand.CommandText = @"delete from studentList where 姓名 =@姓名";

 

myCommand.Parameters.Add(new SqlParameter("@姓名", textBox_Del.Text));

//开始查询

int res = Convert.ToInt32(myCommand.ExecuteNonQuery());

//如果查询不到,报错

if (res == 0)

{

throw new Exception("查无此人");

}

MessageBox.Show("删除成功");



myConnection.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

myConnection.Close();

}

}


06

将修改后的值保存到数据库


1)原来的性别栏下面的数据是男

C#操作SQL数据库


2)将性别由男改为女,按回车,在弹出的提示对话框中点击【确定】

C#操作SQL数据库


3)点击【确定】

C#操作SQL数据库


4)点击【查询数据】,可以看到性别栏的原来的男被改成了女

C#操作SQL数据库


以下为源代码:

//定义一个object类型的变量用来存储修改之前的数据

object cellTempValue = null;

 

//修改之前的数据

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)

{

//将编辑的之前的数据存到cellTempValue变量中

cellTempValue= this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

}

 

 

//修改之后的数据

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)

{

//更新语法

//update 表名 set 列名=值 where 条件

 

//如果修改前的值与修改后的值相等,直接返回不做任何操作

if (object.Equals(cellTempValue, this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value))

{

return;

}

 

//如果选择取消,将修改后的值还原

if (MessageBox.Show("是否确定修改,并更新到数据库", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)

{

this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = cellTempValue;

return;

}

 

//如果选择确认,将修改后的值更新到数据库

try

{

//打开数据库

myConnection.Open();

//实例化命令对象

SqlCommand myCommand = new SqlCommand();

//把要操作的数据库传过来

myCommand.Connection = myConnection;

//操作类型为文本类型

myCommand.CommandType = CommandType.Text;

 

//命令格式

string strSql = String.Format(

"update studentList set {0}='{1}' where 学号='{2}'",

this.dataGridView1.Columns[e.ColumnIndex].HeaderText,//当前选择的列名

this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value,//选中单元格修改后的值

this.dataGridView1.Rows[e.RowIndex].Cells[0].Value//选中单元格修改前的值

) ;

//命令格式

myCommand.CommandText = strSql;

 

//语句执行

int res = myCommand.ExecuteNonQuery();

 

if (res == 0)

{

throw new Exception("修改失败");

}

else

{

MessageBox.Show("修改成功");

}

 

myConnection.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

myConnection.Close();

}

 

}
C#操作SQL数据库

C#操作SQL数据库

苦逼的自动化同胞们,加油!加油!加油!你离成功就差点个赞了,^_^

展开阅读全文

页面更新:2024-03-04

标签:操作   数据库   学号   源代码   性别   命令   姓名   对象   类型   数据

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top