This article mainly introduces the ADO implementation of SQL Server database additions and deletions to the example, very practical value, the need for friends can refer to.
Understand the last one of the introduction of the ADO, we can come to the database for the basic operations such as pruning and checking! The following is a concrete implementation of each operation.
First define the database connection object and connection string in the header of the custom class:
String connectionString = "Data source=sc-201607131829;initial catalog=animal;integrated security=true"; SqlConnection Conn;
1. Query operation of the database, return a 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); Populate the DataSet return DS. Tables[0]; } }
2. Database insert operation, return Boolean value
public bool Doinsert (string name, string skin, String weight) {String sql = "Insert in To Detial (name,skin,weight) VALUES (@name, @skin, @weight) "; Sqlparameter[] Newanimal = {new SqlParameter ("name", name), new SqlParameter ("Skin", skin), new SQL Parameter ("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. Database delete operation, return Boolean value
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. Database update operation, returns a Boolean value
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;}} }
In order to prevent SQL injection, the SqlParameter class is used.