When you create a project, you often write some database operation methods into a class. The following describes the public methods.
///
/// Data Access abstract basic class
///
Public abstract class dbhelpersql (abstract class allowed (but not required) abstract class contains abstract members .)
{
Public static string connectionstring =
Configurationmanager. connectionstrings ["connectionstring1"]. tostring (); // pubconstant. connectionstring;
Public dbhelpersql ()
{
}
# Region Public Method
# Region execute simple SQL statements
# Region Execute SQL statements with Parameters
# Region Stored Procedure operations
......
}// Determine whether the table exists </P> <p> Public static bool tabexists (string tablename) <br/>{< br/> string strsql = "select count (*) from sysobjects where id = object_id (n' ["+ tablename +"] ') and objectproperty (ID, n'isusertable') = 1 "; <br/> Object OBJ = dbhelpersql. getsingle (strsql); <br/> int cmdresult; <br/> If (object. equals (OBJ, null) | (object. equals (OBJ, system. dbnull. value) <br/>{< br/> cmdresult = 0; <br/>}< br/> else <br/>{< br/> cmdresult = int. parse (obj. tostring (); <br/>}< br/> If (cmdresult = 0) <br/>{< br/> return false; <br/>}< br/> else <br/>{< br/> return true; <br/>}< br/>}
Check whether the table object exists in SQL Server:
Select * From DBO. sysobjects where object_id (N 'mytable') and objectproperty (ID, N 'istable') = 1
Object_id: returns the ID of the database object.
N is an explicit conversion of non-Unicode characters into Unicode characters, which comes from the national (UNICODE) data type in the SQL-92 standard for expansion and standardization, where it is not needed, write object_id (mytable ). S
Objectproperty: returns information about objects in the current database. 1 Table "true ". You can also write objectproperty (ID, isusertable) = 1.
/// <Summary>
/// Execute a query result statement and return the query result (object ).
/// </Summary>
/// <Param name = "sqlstring"> calculate the Query Result Statement </param>
/// <Returns> query result (object) </returns>
Public static object getsingle (string sqlstring)
{
Using (sqlconnection connection = new sqlconnection (connectionstring ))
{
Using (sqlcommand cmd = new sqlcommand (sqlstring, connection ))
{
Try
{
Connection. open ();
Object OBJ = cmd. executescalar ();
If (object. Equals (OBJ, null) | (object. Equals (OBJ, system. dbnull. Value )))
// Dbnull refers to the value in the database when a field is not set, which is equivalent to a "null" value in the database ".
// Null indicates null reference in C # (nothing in VB), indicating that no object is referenced.
// Their meanings are different.
{
Return NULL;
}
Else
{
Return OBJ;
}
}
Catch (system. Data. sqlclient. sqlexception E)
{
Connection. Close ();
Throw new exception (E. Message );
}
}
}
}