本篇文章主要介紹了ADO.NET實作對SQL Server資料庫的增刪改查範例,非常具有實用價值,需要的朋友可以參考下。
了解了上一篇的ADO.NET簡介,我們就可以來對資料庫進行增刪改查等基本操作了!下面是每種操作的具體實作。
string connectionString = "Data Source=SC-201607131829;Initial Catalog=Animal;Integrated Security=True"; SqlConnection conn;
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; } } }
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; } } }
更新操作,傳回布林值
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; } } }
以上是ADO.NET實作對SQL Server資料庫的操作教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!