• PGsql(PostgreSQL)的本地连接和远程连接的问题


    刚接收一个项目,数据库是Pgsql,第一次使用这种数据库。安装pgsql后,调试项目时发现:Error: System.Data.Odbc.OdbcException (0x80131937): ERROR [IM002] [Microsoft][ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序。

    好吧解决过程就不说了,直接说方法:这种问题大体分两种,第一,ODBC的问题,第二,配置文件的问题。先说第一,我本机的环境是win7,不知道为什么,pgsql的odbc驱动就是装不上,随后,我把驱动装到server2008服务器上,成功了。随后配置odbc,这里切记

    务必把数据源配置到系统DSN中,至于为什么,你自己慢慢想吧。然后Data Source取决于你在

    <add name="PGSQL1" connectionString="DSN=MAINDB" providerName="System.Data.Odbc"/>

    connectionString="DSN=MaINDB",好吧,这些是基础,我就不废话了。第一结束

    再说第二,配置文件的问题,1.~\PostgreSQL\9.1\data\pg_hba.conf     2. ~\PostgreSQL\9.1\data\ postgresql.conf,要修改这两个文件。还是先说1:

     TYPE  DATABASE        USER            ADDRESS                 METHOD
    
    # IPv4 local connections:
    host    all            all              127.0.0.1/32             md5
    host    all            all              192.168.1.107/32         md5
    

     上面的host 是本机的配置,而下面的,则是你需要远程访问的ip,默认是木有的,你要自己添。2. 我的pgsql装好后,这个配置文件是正常的,也是可用的:

    # - Connection Settings -
    
    listen_addresses = '*'		        # what IP address(es) to listen on;
    					# comma-separated list of addresses;
    					# defaults to 'localhost', '*' = all
    					# (change requires restart)
    port = 5432				# (change requires restart)
    max_connections = 100			# (change requires restart)
    

     所以我也没改。

    第二也说完了

    然后再说说远程访问的事,远程访问,你总不能还用odbc吧,好吧,这里就需要插件了, http://pgfoundry.org/frs/download.php/3226/Npgsql2.0.11.93-bin-ms.net4.0.zip ,这是传送门,或者你也可以根据你的.net版本下载(http://pgfoundry.org/frs/?group_id=1000140&release_id=958),有插件然后最好有个帮助类,好吧。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Npgsql;
    using Mono.Security;
    using System.Configuration;
    using System.Data;

    /// <summary>
    ///PgSqlHelper 的摘要说明
    /// </summary>
    namespace company.Helper{

    public static class Conn
    {
    public static readonly string PgSqlConn = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
    }

    public class PgSqlHelper
    {
    #region 私有构造函数和方法
    private PgSqlHelper() { }
    /// <summary>
    /// 将NpgsqlParameter参数数组(参数值)分配给NpgsqlCommand命令.
    /// 这个方法将给任何一个参数分配DBNull.Value;
    /// 该操作将阻止默认值的使用.
    /// </summary>
    /// <param name="command">命令名</param>
    /// <param name="commandParameters">NpgsqlParameters数组</param>
    private static void AttachParameters(NpgsqlCommand command, NpgsqlParameter[] commandParameters)
    {
    if (command == null) throw new ArgumentNullException("command");
    if (commandParameters != null)
    {
    foreach (NpgsqlParameter p in commandParameters)
    {
    if (p != null)
    {
    // 检查未分配值的输出参数,将其分配以DBNull.Value.
    if ((p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input) &&
    (p.Value == null))
    {
    p.Value = DBNull.Value;
    }
    command.Parameters.Add(p);
    }
    }
    }
    }

    /// <summary>
    /// 将DataRow类型的列值分配到NpgsqlParameter参数数组.
    /// </summary>
    /// <param name="commandParameters">要分配值的NpgsqlParameter参数数组</param>
    /// <param name="dataRow">将要分配给存储过程参数的DataRow</param>
    private static void AssignParameterValues(NpgsqlParameter[] commandParameters, DataRow dataRow)
    {
    if ((commandParameters == null) || (dataRow == null))
    {
    return;
    }
    int i = 0;
    // 设置参数值
    foreach (NpgsqlParameter commandParameter in commandParameters)
    {
    // 创建参数名称,如果不存在,只抛出一个异常.
    if (commandParameter.ParameterName == null ||
    commandParameter.ParameterName.Length <= 1)
    throw new Exception(
    string.Format("请提供参数{0}一个有效的名称{1}.", i, commandParameter.ParameterName));
    // 从dataRow的表中获取为参数数组中数组名称的列的索引.
    // 如果存在和参数名称相同的列,则将列值赋给当前名称的参数.
    if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) != -1)
    commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
    i++;
    }
    }

    /// <summary>
    /// 将一个对象数组分配给NpgsqlParameter参数数组.
    /// </summary>
    /// <param name="commandParameters">要分配值的NpgsqlParameter参数数组</param>
    /// <param name="parameterValues">将要分配给存储过程参数的对象数组</param>
    private static void AssignParameterValues(NpgsqlParameter[] commandParameters, object[] parameterValues)
    {
    if ((commandParameters == null) || (parameterValues == null))
    {
    return;
    }
    // 确保对象数组个数与参数个数匹配,如果不匹配,抛出一个异常.
    if (commandParameters.Length != parameterValues.Length)
    {
    throw new ArgumentException("参数值个数与参数不匹配.");
    }
    // 给参数赋值
    for (int i = 0, j = commandParameters.Length; i < j; i++)
    {
    // If the current array value derives from IDbDataParameter, then assign its Value property
    if (parameterValues[i] is IDbDataParameter)
    {
    IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i];
    if (paramInstance.Value == null)
    {
    commandParameters[i].Value = DBNull.Value;
    }
    else
    {
    commandParameters[i].Value = paramInstance.Value;
    }
    }
    else if (parameterValues[i] == null)
    {
    commandParameters[i].Value = DBNull.Value;
    }
    else
    {
    commandParameters[i].Value = parameterValues[i];
    }
    }
    }

    /// <summary>
    /// 预处理用户提供的命令,数据库连接/事务/命令类型/参数
    /// </summary>
    /// <param name="command">要处理的NpgsqlCommand</param>
    /// <param name="connection">数据库连接</param>
    /// <param name="transaction">一个有效的事务或者是null值</param>
    /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
    /// <param name="commandText">存储过程名或都T-SQL命令文本</param>
    /// <param name="commandParameters">和命令相关联的NpgsqlParameter参数数组,如果没有参数为'null'</param>
    /// <param name="mustCloseConnection"><c>true</c> 如果连接是打开的,则为true,其它情况下为false.</param>
    private static void PrepareCommand(NpgsqlCommand command, NpgsqlConnection connection, NpgsqlTransaction transaction, CommandType commandType, string commandText, NpgsqlParameter[] commandParameters, out bool mustCloseConnection)
    {
    if (command == null) throw new ArgumentNullException("command");
    if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");
    // If the provided connection is not open, we will open it
    if (connection.State != ConnectionState.Open)
    {
    mustCloseConnection = true;
    connection.Open();
    }
    else
    {
    mustCloseConnection = false;
    }
    // 给命令分配一个数据库连接.
    command.Connection = connection;
    // 设置命令文本(存储过程名或SQL语句)
    command.CommandText = commandText;
    // 分配事务
    if (transaction != null)
    {
    if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
    command.Transaction = transaction;
    }
    // 设置命令类型.
    command.CommandType = commandType;
    // 分配命令参数
    if (commandParameters != null)
    {
    AttachParameters(command, commandParameters);
    }
    return;
    }
    #endregion 私有构造函数和方法结束

    #region ExecuteNonQuery命令
    /// <summary>
    /// 执行指定连接字符串,类型的NpgsqlCommand.
    /// </summary>
    /// <remarks>
    /// 示例:
    /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
    /// </remarks>
    /// <param name="connectionString">一个有效的数据库连接字符串</param>
    /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
    /// <param name="commandText">存储过程名称或SQL语句</param>
    /// <returns>返回命令影响的行数</returns>
    public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
    {
    return ExecuteNonQuery(connectionString, commandType, commandText, (NpgsqlParameter[])null);
    }

    /// <summary>
    /// 执行指定连接字符串,类型的NpgsqlCommand.如果没有提供参数,不返回结果.
    /// </summary>
    /// <remarks>
    /// 示例:
    /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new NpgsqlParameter("@prodid", 24));
    /// </remarks>
    /// <param name="connectionString">一个有效的数据库连接字符串</param>
    /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
    /// <param name="commandText">存储过程名称或SQL语句</param>
    /// <param name="commandParameters">NpgsqlParameter参数数组</param>
    /// <returns>返回命令影响的行数</returns>
    public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params NpgsqlParameter[] commandParameters)
    {
    if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
    using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
    {
    connection.Open();
    return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
    }
    }

    /// <summary>
    /// 执行指定数据库连接对象的命令
    /// </summary>
    /// <remarks>
    /// 示例:
    /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
    /// </remarks>
    /// <param name="connection">一个有效的数据库连接对象</param>
    /// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param>
    /// <param name="commandText">存储过程名称或T-SQL语句</param>
    /// <returns>返回影响的行数</returns>
    public static int ExecuteNonQuery(NpgsqlConnection connection, CommandType commandType, string commandText)
    {
    return ExecuteNonQuery(connection, commandType, commandText, (NpgsqlParameter[])null);
    }

    /// <summary>
    /// 执行指定数据库连接对象的命令
    /// </summary>
    /// <remarks>
    /// 示例:
    /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new NpgsqlParameter("@prodid", 24));
    /// </remarks>
    /// <param name="connection">一个有效的数据库连接对象</param>
    /// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param>
    /// <param name="commandText">T存储过程名称或T-SQL语句</param>
    /// <param name="commandParameters">SqlParamter参数数组</param>
    /// <returns>返回影响的行数</returns>
    public static int ExecuteNonQuery(NpgsqlConnection connection, CommandType commandType, string commandText, params NpgsqlParameter[] commandParameters)
    {
    if (connection == null) throw new ArgumentNullException("connection");
    // 创建NpgsqlCommand命令,并进行预处理
    NpgsqlCommand cmd = new NpgsqlCommand();
    bool mustCloseConnection = false;
    PrepareCommand(cmd, connection, (NpgsqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);

    // Finally, execute the command
    int retval = cmd.ExecuteNonQuery();

    // 清除参数,以便再次使用.
    cmd.Parameters.Clear();
    if (mustCloseConnection)
    connection.Close();
    return retval;
    }

    /// <summary>
    /// 执行带事务的NpgsqlCommand.
    /// </summary>
    /// <remarks>
    /// 示例.:
    /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
    /// </remarks>
    /// <param name="transaction">一个有效的数据库连接对象</param>
    /// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param>
    /// <param name="commandText">存储过程名称或T-SQL语句</param>
    /// <returns>返回影响的行数/returns>
    public static int ExecuteNonQuery(NpgsqlTransaction transaction, CommandType commandType, string commandText)
    {
    return ExecuteNonQuery(transaction, commandType, commandText, (NpgsqlParameter[])null);
    }

    /// <summary>
    /// 执行带事务的NpgsqlCommand(指定参数).
    /// </summary>
    /// <remarks>
    /// 示例:
    /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new NpgsqlParameter("@prodid", 24));
    /// </remarks>
    /// <param name="transaction">一个有效的数据库连接对象</param>
    /// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param>
    /// <param name="commandText">存储过程名称或T-SQL语句</param>
    /// <param name="commandParameters">SqlParamter参数数组</param>
    /// <returns>返回影响的行数</returns>
    public static int ExecuteNonQuery(NpgsqlTransaction transaction, CommandType commandType, string commandText, params NpgsqlParameter[] commandParameters)
    {
    if (transaction == null) throw new ArgumentNullException("transaction");
    if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
    // 预处理
    NpgsqlCommand cmd = new NpgsqlCommand();
    bool mustCloseConnection = false;
    PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

    // 执行
    int retval = cmd.ExecuteNonQuery();

    // 清除参数集,以便再次使用.
    cmd.Parameters.Clear();
    return retval;
    }

    #endregion ExecuteNonQuery方法结束

    #region ExecuteDataset方法
    /// <summary>
    /// 执行指定数据库连接字符串的命令,返回DataSet.
    /// </summary>
    /// <remarks>
    /// 示例:
    /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
    /// </remarks>
    /// <param name="connectionString">一个有效的数据库连接字符串</param>
    /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
    /// <param name="commandText">存储过程名称或T-SQL语句</param>
    /// <returns>返回一个包含结果集的DataSet</returns>
    public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
    {
    return ExecuteDataset(connectionString, commandType, commandText, (NpgsqlParameter[])null);
    }

    /// <summary>
    /// 执行指定数据库连接字符串的命令,返回DataSet.
    /// </summary>
    /// <remarks>
    /// 示例:
    /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new NpgsqlParameter("@prodid", 24));
    /// </remarks>
    /// <param name="connectionString">一个有效的数据库连接字符串</param>
    /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
    /// <param name="commandText">存储过程名称或T-SQL语句</param>
    /// <param name="commandParameters">SqlParamters参数数组</param>
    /// <returns>返回一个包含结果集的DataSet</returns>
    public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params NpgsqlParameter[] commandParameters)
    {
    if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
    // 创建并打开数据库连接对象,操作完成释放对象.
    using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
    {
    connection.Open();
    // 调用指定数据库连接字符串重载方法.
    return ExecuteDataset(connection, commandType, commandText, commandParameters);
    }
    }

    /// <summary>
    /// 执行指定数据库连接对象的命令,返回DataSet.
    /// </summary>
    /// <remarks>
    /// 示例:
    /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
    /// </remarks>
    /// <param name="connection">一个有效的数据库连接对象</param>
    /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
    /// <param name="commandText">存储过程名或T-SQL语句</param>
    /// <returns>返回一个包含结果集的DataSet</returns>
    public static DataSet ExecuteDataset(NpgsqlConnection connection, CommandType commandType, string commandText)
    {
    return ExecuteDataset(connection, commandType, commandText, (NpgsqlParameter[])null);
    }

    /// <summary>
    /// 执行指定数据库连接对象的命令,指定存储过程参数,返回DataSet.
    /// </summary>
    /// <remarks>
    /// 示例:
    /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new NpgsqlParameter("@prodid", 24));
    /// </remarks>
    /// <param name="connection">一个有效的数据库连接对象</param>
    /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
    /// <param name="commandText">存储过程名或T-SQL语句</param>
    /// <param name="commandParameters">SqlParamter参数数组</param>
    /// <returns>返回一个包含结果集的DataSet</returns>
    public static DataSet ExecuteDataset(NpgsqlConnection connection, CommandType commandType, string commandText, params NpgsqlParameter[] commandParameters)
    {
    if (connection == null) throw new ArgumentNullException("connection");
    // 预处理
    NpgsqlCommand cmd = new NpgsqlCommand();
    bool mustCloseConnection = false;
    PrepareCommand(cmd, connection, (NpgsqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);

    // 创建NpgsqlDataAdapter和DataSet.
    using (NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
    {
    DataSet ds = new DataSet();
    // 填充DataSet.
    da.Fill(ds);

    cmd.Parameters.Clear();
    if (mustCloseConnection)
    connection.Close();
    return ds;
    }
    }

    /// <summary>
    /// 执行指定事务的命令,返回DataSet.
    /// </summary>
    /// <remarks>
    /// 示例:
    /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
    /// </remarks>
    /// <param name="transaction">事务</param>
    /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
    /// <param name="commandText">存储过程名或T-SQL语句</param>
    /// <returns>返回一个包含结果集的DataSet</returns>
    public static DataSet ExecuteDataset(NpgsqlTransaction transaction, CommandType commandType, string commandText)
    {
    return ExecuteDataset(transaction, commandType, commandText, (NpgsqlParameter[])null);
    }

    /// <summary>
    /// 执行指定事务的命令,指定参数,返回DataSet.
    /// </summary>
    /// <remarks>
    /// 示例:
    /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new NpgsqlParameter("@prodid", 24));
    /// </remarks>
    /// <param name="transaction">事务</param>
    /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
    /// <param name="commandText">存储过程名或T-SQL语句</param>
    /// <param name="commandParameters">SqlParamter参数数组</param>
    /// <returns>返回一个包含结果集的DataSet</returns>
    public static DataSet ExecuteDataset(NpgsqlTransaction transaction, CommandType commandType, string commandText, params NpgsqlParameter[] commandParameters)
    {
    if (transaction == null) throw new ArgumentNullException("transaction");
    if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
    // 预处理
    NpgsqlCommand cmd = new NpgsqlCommand();
    bool mustCloseConnection = false;
    PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

    // 创建 DataAdapter & DataSet
    using (NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
    {
    DataSet ds = new DataSet();
    da.Fill(ds);
    cmd.Parameters.Clear();
    return ds;
    }
    }

    #endregion ExecuteDataset数据集命令结束

    }
    }

    我自己改的sqlhelper,好吧,没什么技术含量。好吧,完了,就这样。

  • 相关阅读:
    C#中的“装箱”与“拆箱”[转贴]
    C#中的委托和事件[转帖]
    ASP.NET的四种错误机制[转帖]
    读技术书的技巧
    《AdvancED ActionScript 3.0 Animation》读书笔记(2) —— 2.5d
    读《JavaScript大师Nicholas C. Zakas谈TypeScript》有感,也谈编译js问题
    《游戏人工智能编程》读书笔记 —— 向量的归一和点乘
    浏览器图形渲染性能测试
    对对碰游戏demo
    A星寻路demo
  • 原文地址:https://www.cnblogs.com/Archosaur/p/PostgreSQL.html
Copyright © 2020-2023  润新知