asp.net 2.0 更新数据库

来源:互联网 发布:基本sql语句 编辑:程序博客网 时间:2024/05/18 01:14
  •  引入命名空间 using System.Data.SqlClient;
public static SqlConnection getConn()
    
{
        SqlConnection conn 
= null;
        
string connStr = string.Empty;

        
try
        
{
            connStr 
= ConfigurationManager.AppSettings["connStr"].ToString();
            
//ConfigurationManager.AppSettings["connStr"]读取Web.Config.xml中的相关自定义的数据库连接字符串
            conn = new SqlConnection(connStr);
        }

        
catch(Exception ex)
        
{
            System.Web.HttpContext.Current.Response.Write(
"数据库连接失败!" + "<br />" +
                
"错误信息:" + ex.Message);
        }

        
finally
        
{
            
if (conn != null)
            
{
                conn.Close();
            }

        }


        
return conn;
    }


public static void executeUpdate(string sql)
    
{
        SqlConnection conn 
= null;
        SqlCommand cmd 
= null;

        
try
        
{
            conn 
= getConn();
            conn.Open();

            cmd 
= new SqlCommand(sql, conn);
            cmd.ExecuteNonQuery();
        }

        
catch(Exception ex)
        
{
            System.Web.HttpContext.Current.Response.Write(
"数据库更新失败!" + "<br />" +
                
"错误信息:" + ex.Message);
        }

        
finally
        
{
            
if (conn != null)
            
{
                conn.Close();
            }

            
if (cmd != null)
            
{
                cmd.Dispose();
            }

        }

    }
原创粉丝点击