ADO.NET实现对SQL Server数据库的增删改查示例

先在自定义类的头部定义好数据库连接对象和连接字符串:

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; } } }

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; } } }

其中为了防止sql注入,用到了SqlParameter类。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjyygz.html