C # Examples of database connection operations

Source: Internet
Author: User
Tags connectionstrings

An XML file was added to the program: app. config

<?xml version= "1.0"?>

<configuration>

<configSections>

<sectiongroup name= "usersettings" type= "System.Configuration.UserSettingsGroup, System, version=4.0.0.0, Culture =neutral, publickeytoken=b77a5c561934e089 ">

<section name= "message.sysfrm" type= "System.Configuration.ClientSettingsSection, System, version=4.0.0.0, Culture=neutral, publickeytoken=b77a5c561934e089 "allowexedefinition=" Machinetolocaluser "requirePermission=" False "/>

<section name= "Message.system" type= "System.Configuration.ClientSettingsSection, System, version=4.0.0.0, Culture=neutral, publickeytoken=b77a5c561934e089 "allowexedefinition=" Machinetolocaluser "requirePermission=" False "/>

</sectionGroup>

</configSections>

<startup>

<supportedruntime version= "v4.0" sku= ". netframework,version=v4.5 "/>

</startup>

<connectionStrings>

<add name= "connstring" connectionstring= "Initial catalog=message; User Id=sa; pwd=112442; Connect timeout=5; "/>

</connectionStrings>

<userSettings>

<Message.sysFrm>

<setting name= "Sysfirststart" serializeas= "String" >

<value>True</value>

</setting>

<setting name= "comsetting" serializeas= "String" >

<value/>

</setting>

<setting name= "portsetting" serializeas= "String" >

<value/>

</setting>

<setting name= "serversetting" serializeas= "String" >

<value/>

</setting>

</Message.sysFrm>

<Message.system>

<setting name= "comsetting" serializeas= "String" >

<value/>

</setting>

</Message.system>

</userSettings>

</configuration>

namespace message{    class dbhelper    {         private static sysfrm syssetting = new sysfrm ();// Define Application settings File         public static readonly string  connstr =  "Data source="  + sysSetting.serverSetting +  system.configuration.configurationmanager.connectionstrings["ConnString"]. connectionstring;        //         public static int executenonquery (string sqlstr, params sqlparameter[]  param)//executenonquery Returns the number of rows affected by the statement and returns if a SELECT statement -1;        {             int res = 0;             using  (SqlconNection conn = new sqlconnection ())              {                 conn. connectionstring = connstr;                 using  (Sqlcommand cmd = new sqlcommand ())                  {                     cmd. commandtext = sqlstr;                     cmd. connection = conn;                     if  (param != null) &NBSP;&NBSP;&NBsp;                      cmd. Parameters.addrange (param);//The  sqlparameter is already included in another  SqlParameterCollection .                      //  Summary: Adds an array of values to the end of  System.Data.SqlClient.SqlParameterCollection .                      //  Parameters: Values: The  System.Data.SqlClient.SqlParameter  value to add.                                           try                     {                         conn. Open ();                         res = cmd. ExecuteNonQuery ();                     }                                              catch  (Exception ex)                      {                         mesSagebox.show (ex. Message);                     }                     //cmd. Parameters.clear ();//The  sqlparameter is already included in another  SqlParameterCollection . Can solve the problem of error, but whether the impact of performance is still to be verified                      return res;                 }             }        }        public  static object executescalar (String sqlstr, params sqlparameter[] param)// Executes the query and returns the first row and first column of the query results &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;     using  (Sqlconnection conn = new sqlconnection ())             {                 conn. connectionstring = connstr;                 using  (Sqlcommand cmd = new sqlcommand ())                  {                     cmd. connection = conn;                     cmd. commandtext = sqlstr;                     if  (param != null)                          cmd. Parameters.addrange (param);                     conn. Open ();//Opening Database                                          return cmd. ExecuteScalar ();                                      }            }         }       &nBsp;public static sqldatareader executereader (String sqlstr, params sqlparameter [] param)         {             sqlconnection conn = new sqlconnection ();             conn. connectionstring = connstr;             using  (Sqlcommand cmd = new sqlcommand ())              {                 cmd. connection = conn;                 cmd. commandtext = sqlstr;                 if  (param != null)                      cmd. Parameters.addrange (param);                                  try                {                      conn. Open ();                                }                 catch  (System.exception ex)                 {                     messagebox.show ("Error getting database server and instance in network! "  + ex. ToString (),  "hint", messageboxbuttons.ok, messageboxicon.information);                     return null;                 }                 sqldatareader dr  = cmd. ExecuteReader (commandbehavior.closeconnection);                 return dr;             }        }         public static DataTable DataAdapter (String sqlstr, params sqlparameter[] param)          {                  sqldataadapter da = new sqldataadapter (SQLSTR,&NBSP;CONNSTR);             datatable dt = new datatable () ;             da. SelectCommand.Parameters.AddRange (param);             //dataset ds = new dataset ();             da. Fill (DT);            int ias =    dt. rows.count;            for  (int i =  0; i <&nBsp;dt. Rows.count; ++i)             {                 datarow dr =  dt. rows[i];            }             return dt;         }    }    }


This article is from the "Radisson Blu Still" blog, please be sure to keep this source http://wangwentao2015.blog.51cto.com/5601365/1689848

C # Examples of database connection operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.