利用NPgsql 在PostgreSQL中创建和删除数据库

1. App.config:

<add key="ShpPostgresConn" value="Server=10.10.1.40;Port=5432;User Id=postgres;Password=123456;Database=postgres;"/>

2. 利用NPgsql来创建和删除数据库代码:

代码
    /// <summary>
    
/// Author: qzhang
    
/// Date: 2010-11-2
    
/// Description:  This class offers the function of accessing the postgresql database
    
/// </summary>
    public class ShapeInfoDAL
    {
        
private static string connStr = System.Configuration.ConfigurationManager.AppSettings["ShpPostgresConn"];

        
/// <summary>
        
/// Create the database by the database name
        
/// </summary>
        
/// <param name="databaseName">the database name</param>
        
/// <returns>true: create database successfully; false: not</returns>
        public static bool CreateDatabase(string databaseName)
        {
            NpgsqlConnection conn 
= null;

            
try
            {
                conn 
= new NpgsqlConnection(connStr);
                conn.Open();
                
string cmdText = "CREATE DATABASE \"" + databaseName + "\" "
                               
+ "WITH OWNER = postgres "
                               
+ "TEMPLATE=template_postgis "
                               
+ "ENCODING = 'UTF8' "
                               
//+ "LC_COLLATE = 'Chinese (Traditional), Taiwan'"
                               
//+ "LC_CTYPE = 'Chinese (Traditional), Taiwan'"
                               + "CONNECTION LIMIT = -1; ";
                NpgsqlCommand command 
= new NpgsqlCommand(cmdText, conn);
                command.ExecuteNonQuery();
                conn.Close();
            }
            
catch (NpgsqlException ex)
            {
                
if (conn != null)
                {
                    conn.Close();
                }

                
return false;
            }

            
return true;
        }

        
/// <summary>
        
/// Delete the database by the database name
        
/// </summary>
        
/// <param name="databaseName">the database name</param>
        
/// <returns>true: delete the database successfully; false: not</returns>
        public static bool DeleteDatabase(string databaseName)
        {
            NpgsqlConnection conn 
= null;

            
try
            {
                conn 
= new NpgsqlConnection(connStr);
                conn.Open();
                
string cmdText = "DROP DATABASE \"" + databaseName + "\" ";
                NpgsqlCommand command 
= new NpgsqlCommand(cmdText, conn);
                command.ExecuteNonQuery();
                conn.Close();
            }
            
catch (NpgsqlException ex)
            {
                
if (conn != null)
                {
                    conn.Close();
                }

                
return false;
            }

            
return true;
        }
    }

 

posted @ 2010-11-02 22:20  zqblog007  阅读(443)  评论(0编辑  收藏  举报