The connection database is encapsulated into classes, reducing code redundancy and enhancing code readability.
1. Construction of Class
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Data.SqlClient;
Using System.Data;
Namespace Test {public class Dbsql {public SqlConnection conn = null;
Public SqlDataAdapter da = null;
Public SqlCommand com = null; Public Dbsql () {//string connstr = "server=.;D
Atabase=library;uid=sa;pwd=123 ";
conn = new SqlConnection (CONNSTR);
com = new SqlCommand (); Com.
Connection = conn; String connstr = "server=.;D
Atabase=library;uid=sa;pwd=123 ";
conn = new SqlConnection (CONNSTR);
com = new SqlCommand (); Com.
Connection = conn;
da = new SqlDataAdapter ("", conn);
///<summary>///Returns the query result as a DataTable based on the query statement, and the return value is meaningless if the various update statements are executed. </summary>///<param name= "Selectsql" ></param>///<returns> Query Results </returns> Public DataTable Filldt (string selectsql) {//com.
CommandType = CommandType.Text; Com.
CommandText = "SELECT * from student";
da = new SqlDataAdapter (COM);
DataTable dt = new DataTable (); Da.
Fill (DT);
return DT;
DataTable dt = new DataTable (); Da.
SelectCommand.CommandText = Selectsql; Da.
Fill (DT);
return DT; ///<summary>///Execute various SQL statements///</summary>///<param name= "SQL" >true
Indicates execution success, false indicates execution failure </param>///<returns></returns> public bool Execsql (string Sql)
{bool R = false; Conn.
Open (); Com.
Connection = conn; Com.
CommandType = CommandType.Text; Com.
CommandText = SQL; Com.
ExecuteNonQuery (); Conn.
Close ();
R = True;
return R; }
}
} 2. Class is used
Dbsql db = new Dbsql (); The instantiated DataTable of the class
dt = new DataTable ();
String strSQL = "INSERT into student (Sno,sname,ssex,sage) VALUES (' 3 ', ' Wang Peng ', ' Men ',)";
Db. Execsql (strSQL); Invokes the Execsql () method of the class, which implements the defined strSQL statement
dt = db. Filldt ("SELECT * from student"); Invoke the Filldt () method of the class to implement a query to the database this
. Gridview1.datasource = DT;
This. Gridview1.databind ();