2016-05-17 84 views
0

我想將PostgreSQL數據庫連接到C#控制檯應用程序。這是我的代碼:C中的postgres異常#

static void Main(string[] args) 
{ 
    string connstring = String.Format("Server=localhost;Port=5432;" + 
        "User Id=postgres;Password=admin;Database=mydb;"); 
    NpgsqlConnection conn = new NpgsqlConnection(connstring); 
    conn.Open(); 

    string sql = string.Format("CREATE TABLE public.stvari2 ime text, broj smallint, id integer)"); 
    NpgsqlCommand cmd = new NpgsqlCommand(sql, conn); 
    cmd.ExecuteNonQuery(); 
} 

我從字面上複製了來自Postgres的反向工程SQL查詢,所以我懷疑這是問題所在。總之,當我運行它,我得到一個異常:

類型的未處理的異常「Npgsql.PostgresException」發生在Npgsql.dll

在最後一行(的ExecuteNonQuery)。 任何想法?在您的SQL字符串

回答

3

展望 - 是否缺少(

string sql = string.Format("CREATE TABLE public.stvari2 ime text, broj smallint, id integer)"); 

在這裏不要你需要另一個( - > public.stvari2(IME

string sql = string.Format("CREATE TABLE public.stvari2(ime text, broj smallint, id integer)"); 
0

嘗試這個樣子將工作

static void Main(string[] args) 
     { 

      String connections = "Server=192.168.1.163;Port=5432;Database=postgres;User Id=postgres;Password=root;"; 
      NpgsqlConnection connection = new NpgsqlConnection(); 
      connection.ConnectionString = connections; 
      connection.Open(); 

      try 
      { 
       NpgsqlCommand cmd = new NpgsqlCommand(); 
       cmd.Connection = connection; 
       cmd.CommandText = "INSERT INTO sector(name,address,designition,description,auto_id) values ('vinoth','chennai','sds','wdewd','123')"; 
       cmd.CommandType = CommandType.Text; 
       cmd.ExecuteNonQuery();               
       cmd.Dispose(); 

      } 
      catch (Exception e) 
      { 
       e.ToString(); 
      } 
}