【c# 数据库】对数据库进行增删查改

1.DataGridView链接数据库

2.链接数据库

using System.Data.SqlClient;

SqlConnection con = null; //创建SqlConnection 的对象
string input = EnterText.Text;
try //try里面放可能出现错误的代码
{

string str = "data source=.;initial catalog=student;Integrated Security=True";

con = new SqlConnection(str);

con.Open(); //打开数据库

//以上操作为登录数据库的操作

3.查询

扫描二维码关注公众号,回复: 5740433 查看本文章

SqlConnection con = null; //创建SqlConnection 的对象
string input = "'"+EnterText.Text+"%'";//*********实现模糊查询


try //try里面放可能出现错误的代码
{

string str = "data source=.;initial catalog=student;Integrated Security=True";

con = new SqlConnection(str);

con.Open(); //打开数据库

//以上操作为登录数据库的操作

string sql = "select * from studentsinfo where 学号 like" + input + "or 姓名 like" + input + "or 性别 like" + input + "or 总分 like" + input;//实现无特定条件查询
SqlCommand com = new SqlCommand(sql, con);
SqlDataAdapter sda = new SqlDataAdapter(com);
DataSet ds = new DataSet();
sda.Fill(ds, "show");
dataGridView2.DataSource = ds;//链接到新的表格并显示
dataGridView2.DataMember = "show";


}
catch (Exception) //当try中有错误则执行catch中的代码,否则不执行
{
MessageBox.Show("网络异常!");

}

finally //无论如何都会执行finally中的代码
{

if (con != null) //判断con不为空
{
con.Close();

}
}
}

 4.增加数据

SqlConnection con = null; //创建SqlConnection 的对象
string input = "'" + EnterText.Text + "'";
try //try里面放可能出现错误的代码
{

string str = "data source=.;initial catalog=student;Integrated Security=True";

con = new SqlConnection(str);

con.Open(); //打开数据库

//以上操作为登录数据库的操作

string str1 = name.Text;
string str2 = id.Text;
string str3 = sex.Text;
string str4 = score.Text;
string add = str1 + "','" + str2 + "','" + str3 + "','" + str4;
string uinput = "insert into studentsinfo values ( '" + add + "')";//sql插入语句
SqlCommand com = new SqlCommand(uinput, con);
com.ExecuteScalar();
MessageBox.Show("finish!");//提示成功插入
}
catch (Exception) //当try中有错误则执行catch中的代码,否则不执行
{
MessageBox.Show("网络异常!");

}

finally //无论如何都会执行finally中的代码
{

if (con != null) //判断con不为空
{
con.Close();

}
}

5.删除数据

SqlConnection con = null; //创建SqlConnection 的对象
string input = "'" + EnterText.Text + "'";
try //try里面放可能出现错误的代码
{

string str = "data source=.;initial catalog=student;Integrated Security=True";

con = new SqlConnection(str);

con.Open(); //打开数据库

//以上操作为登录数据库的操作

string sql = "delete from studentsinfo where 学号 =" + input + "or 姓名 =" + input + "or 性别 =" + input + "or 总分 =" + input;

SqlCommand com = new SqlCommand(sql, con);
com.ExecuteScalar();
MessageBox.Show("finish!");


}
catch (Exception) //当try中有错误则执行catch中的代码,否则不执行
{
MessageBox.Show("网络异常!");

}

finally //无论如何都会执行finally中的代码
{

if (con != null) //判断con不为空
{
con.Close();

}
}
}

}

猜你喜欢

转载自www.cnblogs.com/SeasonBubble/p/10638823.html
今日推荐