C#链接数据库 增删改查的语句 详细

如题所述

用到
using System.Data.SqlClient;//命名空间
SQL 查询
string connection_str=@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ChatRoom;Data Source=.\sqlexpress";

string select_str="select 字段 from 表名 [where 字段=值]";//"[之间的内容]"是可选的

SqlConnection con=new SqlConnection(connection_str);//一,创建数据库连接对象
SqlCommand com=new SqlCommand(select_str,con);//二,创建数据操作对象
con.Open();//现在用的是连接操作方法,所以要先打开这个数据连接对象的连接
DataReader _dataReader = com.ExcuteReader();
while(_dataReader.Next())//遍历
{
string temp += dataReader["字段"].ToString()+"\r\n";
}
con.Close();//关闭数据库连接对象
MessageBox.Show(temp);

以上这种方法是称为连接式操作。

以下这种方法是称为非连接式操作。
using System.Data.SqlClient;//因为要用到SQL对象
using System.Data;//要用到数据集对象,如以下将要用到:DataSet对象
string connection_str=@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ChatRoom;Data Source=.\sqlexpress";

string select_str="select 字段 from 表名 [where 字段=值]";//"[之间的内容]"是可选的

SqlConnection con=new SqlConnection(connection_str);//一,创建数据库连接对象
SqlDataAdapter DataAdapter=new SqlDataAdapter(select_str,con);//二,创建数据操作对象
DataSet ds=new DataSet();
DataAdapter.Fill(ds);//DataAdapter.Fill(填充对象)//函数是将除处理的select_str语句得来结果填充到指定的填充对象
string temp="";
foreact(DataRow dr in ds.Table[0].Rows)//遍历
{
temp+=dr["字段"].ToString();
}
MessageBox.Show(temp);

至少楼主说的要增删改查。

就是修改select_str字符串就行了。

select(查询):"Select 字段 from 表名 [where 条件]";
update(更新):"Update 列名 set 字段=值 [where 条件]";
insert(插入):"Insert [into] 表名 Values(字段[,字段,...,...]) [where 条件]";
delete(删除):"delect from 表名 [where 条件]";

当然,除了select(查询)是有返回数据,其它update(更新),insert(插入),delete(删除)都只是返回操作状态值。
温馨提示:内容为网友见解,仅供参考
无其他回答