//增加、删除、更新、查询公用
string MyConn = "server=127.0.0.1;uid=数据库登录名;pwd=密码;database=数据库的名字;Trusted_Connection=no";
SqlConnection MyConnection = new SqlConnection(MyConn);
string MyInsert = "想要执行的sql语句";
SqlCommand MyCommand = new SqlCommand(MyInsert, MyConnection);
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
2、删除
string MyDelete = "想要执行的sql语句";
SqlCommand MyCommand = new SqlCommand(MyDelete, MyConnection);
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
3、更新
string MyUpdate = "想要执行的sql语句";
SqlCommand MyCommand = new SqlCommand(MyUpdate, MyConnection);
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();
4、查询
MyConn.Open();
SqlDataAdapter dap = new SqlDataAdapter("想要执行的sql语句",MyConn);
DataSet ds = new DataSet();//实例化DataSet类
dap.Fill(ds, "Table");//添加SQL语句并执行
dataGridView1.DataSource = ds.Tables[0].DefaultView;//显示数据
本文提供了一套使用C#进行SQL操作的实用代码示例,包括如何连接数据库、执行增删改查等基本操作。通过具体的代码片段,读者可以快速了解如何在自己的应用程序中实现这些功能。
1039

被折叠的 条评论
为什么被折叠?



