2015-12-21 57 views
0

当我尝试连接到DataBase时,出现错误:关键字不支持:主机。使用带有dotConnect的Visual Studio无法连接到postrgres

 int x = Int32.Parse(textBox1.Text); 
     try 
     { 

      System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(); 
      con.ConnectionString = 
      Properties.Settings.Default.postgresConnectionString; 
      System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); 
      cmd.Connection = con; 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.CommandText = "getCount"; 
      System.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter("@k", 
      SqlDbType.Int); 
      param.Direction = ParameterDirection.Output; 
      cmd.Parameters.Add(param); 
      cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Tovar", x)); 
      con.Open(); 
      cmd.ExecuteNonQuery(); 
      string kolvo = cmd.Parameters["@k"].Value.ToString(); 
      con.Close(); 
      label1.Text = kolvo + " израсходован в количестве "; 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

连接字符串:

User Id=postgres;Password=8loz9fnl;Host=localhost;Database=postgres;Persist Security Info=True 

enter image description here

+0

你为什么不使用'NpgsqlConnection'(或者' OdbcConnection'?)而不是'SqlConnection'? SQL Server提供程序具有“数据源”,而不是“主机”。还可以使用'using'语句来处理连接和命令automaticalliy,而不是手动调用'Close'方法。 –

+0

为什么不使用[Npgsql](http://www.npgsql.org/doc/)?,只要看看这个[教程](http://www.codeproject.com/Articles/30989/Using- PostgreSQL-in-your-C-NET-application-An-intr) –

+0

@wingedpanther谢谢你,连接工作,但我得到了这个结果“输出参数'@k'的值在命令执行结果中不存在。参数的名称:@k –

回答

2

我猜您使用devart对ado.net连接dotconnect所以你应该导入Devart.Data.PostgreSql和使用PgSqlConnection代替sqlconnectionpgsqlcommand代替sqlcommand

0

正如其他人已经提到的,你需要使用Npgsql。还可以使用导入来简化代码。例如连接代码: 导入部件using Npgsql;然后得到一个连接,打开它

using (var conn = new NpgsqlConnection(Properties.Settings.Default.postgresConnectionString)) 
{ 
    // you other code here 
} 

这样,你的资源自动管理,你不需要调用close方法,你也需要改变类型作为@wingedpanther提到的命令。阅读一个好的教程或提到的文档将会有很大的帮助。 你也需要修复您的连接字符串:

Server=localhost;User Id=postgres;Password=8loz9fnl;Database=postgres;Persist Security Info=True 

,并避免将您的实际用户名和密码。

相关问题