ADO.NET如何實現對SQL Server數據庫的增刪改查?

ADVERTISEMENT

ADO.NET如何實現對SQL Server數據庫的增刪改查?

了解了上一篇的ADO.NET簡介,我們就可以來對數據庫進行增刪改查等基本操作了!下面是每種操作的具體實現。

先在自定義類的頭部定義好數據庫連接對象和連接字符串:


 string connectionString = "Data Source=SC-201607131829;Initial Catalog=Animal;Integrated Security=True";
 SqlConnection conn;
ADVERTISEMENT

1.數據庫的查詢操作,返回一個DataTable


 public DataTable doSelect()
 {
 
 string sql = "select * from detial";
 
 using (conn = new SqlConnection(connectionString))
 {
 
 conn.Open();
 
 SqlDataAdapter da = new SqlDataAdapter(sql, conn);
 
 DataSet ds = new DataSet();
 
 da.Fill(ds); //填充DataSet
 
 return ds.Tables[0];
 
 }
 }

2.數據庫插入操作,返回布爾值


 public bool doInsert(string name, string skin, string weight)
 {
 
 string sql = "insert into detial(name,skin,weight)values(@name,@skin,@weight)";
 
 SqlParameter[] newAnimal = {
 new SqlParameter("name",name),
 new SqlParameter("skin",skin),
 new SqlParameter("weight",skin)
 };
 
 using (conn = new SqlConnection(connectionString))
 {
 SqlCommand com = new SqlCommand(sql, conn);
 try
 {
 if (newAnimal != null)
 {
 foreach (SqlParameter parameter in newAnimal)
 {
 com.Parameters.Add(parameter);
 
 }
 }
 conn.Open();
 
 int influence = com.ExecuteNonQuery();
 
 if (influence > 0)
 {
 
 return true;
 }
 else
 {
 
 return false;
 }
 }
 catch (Exception exception)
 {
 return false;
 }
 }
 }
 

3.數據庫刪除操作,返回布爾值


 public bool doDelete(string name)
 {
 
 string sql = "delete from detial where name = @name";
 
 SqlParameter[] deleteParameter = { new SqlParameter("name", name) };
 
 using (conn = new SqlConnection(connectionString))
 {
 
 SqlCommand com = new SqlCommand(sql, conn);
 
 try
 {
 
 if (deleteParameter != null)
 {
 foreach (SqlParameter parameter in deleteParameter)
 {
 com.Parameters.Add(parameter);
 }
 
 }
 
 conn.Open();
 
 int influence = com.ExecuteNonQuery();
 
 if (influence > 0)
 {
 
 return true;
 }
 else
 {
 
 return false;
 }
 }
 catch (Exception exception)
 {
 return false;
 }
 }
 }
 

4.數據庫更新操作,返回布爾值


 public bool doUpdate(string name , string skin) {
 
 string sql = "update detial set skin = @skin where name = @name";
 SqlParameter[] updateParameter = {
 new SqlParameter("name",name),
 new SqlParameter("skin",skin)
 };
 
 using (conn = new SqlConnection(connectionString)) {
 
 SqlCommand com = new SqlCommand(sql,conn);
 
 try {
 
 if (updateParameter != null) { 
 
 foreach(SqlParameter parameter in updateParameter){
 
 com.Parameters.Add(parameter);
 
 } 
 }
 
 conn.Open();
 
 int influence = com.ExecuteNonQuery();
 
 if (influence > 0)
 {
 
 return true;
 }
 else
 {
 
 return false;
 }
 
 }catch(Exception exception){
 
 return false;
 }
 }
 
 }
 
 
ADVERTISEMENT

其中為了防止sql注入,用到了SqlParameter類。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持路飯。


本文地址:
ADVERTISEMENT
ADVERTISEMENT