Error database driver unknown driver postgres forgotten import

With using the version of the pq.go driver from the "over" branch I can get the package to build and install, but when I import the driver and try to connect the connection fails with thi...

@vendion

With using the version of the pq.go driver from the «over» branch I can get the package to build and install, but when I import the driver and try to connect the connection fails with this error:

panic: sql: unknown driver "postgres" (forgotten import?)

the way that I am importing it is as follows:

import (
    "fmt"
    "os"
    "database/sql"
    _ "github.com/bmizerany/pg.go"
)

My connect statement is this line:

db, err := sql.Open("postgres", "dbname=pgtest user=pguser password=password port=5432")

My version of Go is:

go version weekly.2012-03-04 +5c664f190e4e

Am I doing something wrong or is this an issue with the driver?

@bmizerany

I renamed it to github.com/bmizerany/pq

Please try it on the over branch and let me know if you have the same problem.

On Mar 7, 2012, at 7:42 AM, Adam Jimersonreply@reply.github.com wrote:

With using the version of the pq.go driver from the «over» branch I can get the package to build and install, but when I import the driver and try to connect the connection fails with this error:

panic: sql: unknown driver "postgres" (forgotten import?)

the way that I am importing it is as follows:

import (
   "fmt"
   "os"
   "database/sql"
   _ "github.com/bmizerany/pg.go"
)

My connect statement is this line:

db, err := sql.Open("postgres", "dbname=pgtest user=pguser password=password port=5432")

My version of Go is:

go version weekly.2012-03-04 +5c664f190e4e

Am I doing something wrong or is this an issue with the driver?


Reply to this email directly or view it on GitHub:
#15

@vendion

When did you rename the package because I built it today and the package is still named github.com/bmizerany/pq.go.a

ls github.com/bmizerany/
pq.go.a

I manually cloned the repository and checkout the over branch and ran go install on that. Here is what I am testing with:

package main

import (
        "os"
        "database/sql"
        _ "github.com/bmizerany/pq"
)

func main() {
        _, err := sql.Open("postgres", "dbname=pgtest user=pguser password=password port=5432")
        if err != nil {
                panic(err)
        }
        os.Exit(0)
}

@vendion

Ah it is because the repository is named pq.go, when go get is ran or if a git clone is done without explicitly naming the directory name then when the package gets built Go assumes the package name from the directory name and not the package pq line in the conn.go file.

so a work around for this would have to be something like:

git clone git://github.com/bmizerany/pq.go.git pq
git branch over && git checkout over
git pull origin over
go install .

or a very destructive (due to the number of forks your project has) renaming of the repository.

@bmizerany

No. bmizerany/pq.go is now one file a major syntax error, on
purpose. Use bmizerany/pq.

On Wed, Mar 7, 2012 at 12:38 PM, Adam Jimerson
reply@reply.github.com
wrote:

Ah it is because the repository is named pq.go, when go get is ran or if a git clone is done without explicitly naming the directory name then when the package gets built Go assumes the package name from the directory name and not the package pq line in the conn.go file.

so a work around for this would have to be something like:

git clone git://github.com/bmizerany/pq.go.git pq
git branch over && git checkout over
git pull origin over
go install .

or a very destructive (due to the number of forks your project has) renaming of the repository.


Reply to this email directly or view it on GitHub:
#15 (comment)

@vendion

Sorry what do you mean by bmizerany/pq.go is a major syntax error on
purpose?

As it stands now if some one was to run go get github.com/bmizerany/pq.go or git clone git:// github.com/bmizerany/pq.go.git they get the following directory layout
in their $GOPATH github.com/bmizerany/pq.go from there there in the
user runs go {install|build} github.com/bmizerany/pq.go they get a
package named pq.go.a. If the pq.go directory were to be renamed pq.go -> pq and then go {install|build} github.com/bmizerany/pq then
they get a package named pq.a.

It seems another way to build or install the package would be to do go {install|build} github.com/bmizerany/pq.go/conn.go because that would
cause it to use the package declaration instead.

In short after building the package as pq.a instead of pq.go.a
and importing that
I was able to connect to my Postgres database and runs sample select
statement.

On Wed, Mar 7, 2012 at 3:54 PM, Blake Mizerany <
reply@reply.github.com

wrote:

No. bmizerany/pq.go is now one file a major syntax error, on
purpose. Use bmizerany/pq.

On Wed, Mar 7, 2012 at 12:38 PM, Adam Jimerson
reply@reply.github.com
wrote:

Ah it is because the repository is named pq.go, when go get is ran
or if a git clone is done without explicitly naming the directory
name then when the package gets built Go assumes the package name from the
directory name and not the package pq line in the conn.go file.

so a work around for this would have to be something like:

git clone git://github.com/bmizerany/pq.go.git pq
git branch over && git checkout over
git pull origin over
go install .

or a very destructive (due to the number of forks your project has)
renaming of the repository.


Reply to this email directly or view it on GitHub:
#15 (comment)


Reply to this email directly or view it on GitHub:
#15 (comment)

@bmizerany

Shit. Sorry. I got confused. I renamed a bunch of repos yesterday as a
result of the new behavior in go get. I forgot I haven’t moved over
pq.go. I’m sorry.

You’re correct. You need to rename the directory from pq.go ro pq
or clone it as pq into your GOPATH.

As for the syntax error, this is what pq.go will look like when the
move is complete:
https://github.com/bmizerany/pat.go/blob/master/pat.go

On Wed, Mar 7, 2012 at 1:22 PM, Adam Jimerson
reply@reply.github.com
wrote:

Sorry what do you mean by bmizerany/pq.go is a major syntax error on
purpose?

As it stands now if some one was to run go get github.com/bmizerany/pq.go or git clone git:// github.com/bmizerany/pq.go.git they get the following directory layout
in their $GOPATH github.com/bmizerany/pq.go from there there in the
user runs go {install|build} github.com/bmizerany/pq.go they get a
package named pq.go.a.  If the pq.go directory were to be renamed pq.go -> pq and then go {install|build} github.com/bmizerany/pq then
they get a package named pq.a.

It seems another way to build or install the package would be to do go {install|build} github.com/bmizerany/pq.go/conn.go because that would
cause it to use the package declaration instead.

In short after building the package as pq.a instead of pq.go.a
and importing that
I was able to connect to my Postgres database and runs sample select
statement.

On Wed, Mar 7, 2012 at 3:54 PM, Blake Mizerany <
reply@reply.github.com

wrote:

No. bmizerany/pq.go is now one file a major syntax error, on
purpose. Use bmizerany/pq.

On Wed, Mar 7, 2012 at 12:38 PM, Adam Jimerson
reply@reply.github.com
wrote:

Ah it is because the repository is named pq.go, when go get is ran
or if a git clone is done without explicitly naming the directory
name then when the package gets built Go assumes the package name from the
directory name and not the package pq line in the conn.go file.

so a work around for this would have to be something like:

git clone git://github.com/bmizerany/pq.go.git pq
git branch over && git checkout over
git pull origin over
go install .

or a very destructive (due to the number of forks your project has)
renaming of the repository.


Reply to this email directly or view it on GitHub:
#15 (comment)


Reply to this email directly or view it on GitHub:
#15 (comment)


Reply to this email directly or view it on GitHub:
#15 (comment)

@vendion

No worries we all have days like that, glad that this was cleared up.

ritd

0 / 0 / 0

Регистрация: 11.02.2022

Сообщений: 6

1

24.02.2022, 15:45. Показов 3826. Ответов 6

Метки нет (Все метки)


Доброго дня!

есть код:

Go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package store
 
import (
    _ "github.com/jackc/pgx/v4"
    _ "github.com/jackc/pgx/v4/pgxpool"
    "github.com/jmoiron/sqlx"
)
 
type Store struct {
    config *Config
    db *sqlx.DB
}
 
func New (config *Config) *Store{ //Store
    return &Store{
        config: config,
    }
}
 
func (s *Store) Open () error {
     db, err := sqlx.Connect("postgres", s.config.DataBaseUrl)
    if err != nil {
        return err
    }
 
 
 
    if err:= db.Ping();err!= nil{
        return err
    }
    s.db = db
    return nil
}
 
func (s *Store) Close () {
    s.db.Close()
}

Возникает паника в sqlx.Connect: unknown driver «postgres» (forgotten import?) Не пойму, чего он от меня хочет.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Эксперт Java

4016 / 2618 / 475

Регистрация: 28.04.2012

Сообщений: 8,422

24.02.2022, 16:12

2

ritd, он хочет, чтобы ты указал правильное имя драйвера



0



0 / 0 / 0

Регистрация: 11.02.2022

Сообщений: 6

24.02.2022, 17:19

 [ТС]

3

А мое-то «postgres» чем ему не угодило ?



0



Эксперт Java

4016 / 2618 / 475

Регистрация: 28.04.2012

Сообщений: 8,422

24.02.2022, 19:09

4

ritd, тем, что оно не для того драйвера, который ты используешь



0



ritd

0 / 0 / 0

Регистрация: 11.02.2022

Сообщений: 6

24.02.2022, 19:30

 [ТС]

5

«pqx» вместо «postgres» выдавало sqlx.Connect: unknown driver «pqx» (forgotten import?)

Ладно, как-то так сделал:

Go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package store
 
import (
    "context"
    _ "github.com/jackc/pgx/v4"
    "github.com/jackc/pgx/v4/pgxpool"
)
 
type Store struct {
    config *Config
    //db *sqlx.DB
    db *pgxpool.Pool
}
 
func New(config *Config) *Store { //Store
    return &Store{
        config: config,
    }
}
 
 
func (s *Store) Open(ctx context.Context) error {
 
    cfg, err := pgxpool.ParseConfig(s.config.DataBaseUrl)
    if err != nil {
        return err
    }
    pool, err := pgxpool.ConnectConfig(ctx, cfg)
    if err != nil {
        return err
    }
 
    err = pool.Ping(ctx)
            if err != nil{
        return err
    }
    s.db = pool
    return nil
}



0



Эксперт Java

4016 / 2618 / 475

Регистрация: 28.04.2012

Сообщений: 8,422

26.02.2022, 02:46

6

Цитата
Сообщение от ritd
Посмотреть сообщение

«pqx» вместо «postgres» выдавало sqlx.Connect: unknown driver «pqx» (forgotten import?)

Может, потому что pqx и pgx — не одно и то же?



0



Garry Galler

Эксперт Python

5403 / 3827 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

28.02.2022, 17:04

7

ritd,
Достаточно было зайти на github pgx:

Support for pgx was merged into sqlx on November 1, 2014.

Go
1
db, err := sqlx.Connect("pgx", "postgres://pgx_md5:secret@localhost:5432/pgx_test")



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

28.02.2022, 17:04

Помогаю со студенческими работами здесь

Переделка из делфи — ругается на объявление функции «sizeof «Check» is unknown or zero»
Сижу перебираю программку с одного языка на другой, выскочила проблема. Я на сях уже ничего давно…

«WDF» & «Driver samples for Windows 10» репозитории на github
Наткнулся на несколько свежих репозиториев Microsoft которые могут быть интересны разработчикам…

Как написать регулярное выражение для выдергивания английских букв и символов: «+», «,», «:», «-«, » «, «!», «?» и «.»
Не могу ни как собразить как написать регулярное выражение для выдергивания английских букв и…

В зависимости от времени года «весна», «лето», «осень», «зима» определить погоду «тепло», «жарко», «холодно», «очень холодно»
В зависимости от времени года &quot;весна&quot;, &quot;лето&quot;, &quot;осень&quot;, &quot;зима&quot; определить погоду &quot;тепло&quot;,…

Получить значение из {«text1″:»val1″,»text2″:»val2″,»text3»:{«text»:»val»}}
Есть такая строка
var my = ‘{&quot;text1&quot;:&quot;val1&quot;,&quot;text2&quot;:&quot;val2&quot;,&quot;text3&quot;:{&quot;text&quot;:&quot;val&quot;}}’;
Как из…

На машине клиента «QSQLITE» выдает: Driver not loaded Driver not loaded
#include &lt;QSqlDatabase&gt;
#include &lt;QSqlQuery&gt;
#include &lt;QSqlRecord&gt;
#include &lt;QSqlError&gt;…

Текстовый редактор с функциями «найти»,»заменить»,»удалить»,»выделить всё»,»время и дата»,»отменить»
Здравствуйте.
Делаю Текстовый редактор,по типу Блокнота,помогите реализовать следующие…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

7

Вы импортировали sql/database, пакет содержит общий интерфейс для операций, связанных с sql.

Поскольку это только общий интерфейс, вам необходимо импортировать конкретную реализацию интерфейса, и в данном контексте это драйвер базы данных.

Из вашего кода: sql.Open(«postgres», psqlInfo), я полагаю, вы используете базу данных postgresql. Доступно несколько драйверы postgresql для golang, один из них — драйвер https://github.com/lib/pq. Так что добавьте его в оператор импорта.

package main

import (
    "bufio"
    "database/sql"
    "encoding/csv"
    "encoding/json"
    "fmt"
    "io"
    "log"
    "os"
    _ "github.com/lib/pq" // <------------ here
)

Драйвер базы данных pq должен быть импортирован с символом _ перед оператором импорта. Это потому, что мы не используем его явно в коде, хотя он по-прежнему требуется для пакета database/sql. Для получения дополнительных сведений см. Соответствующий вопрос SO Что означает подчеркивание перед оператором импорта?.

Дополнительная информация о golang sql: https://pkg.go.dev/database/sql.
.

Я пытаюсь запустить миграцию в своем API отдыха go-fiber, используя golang-migrate.

Я добавил команды для запуска миграций в make-файл. Однако, когда я запускаю make migrateup, я получаю следующую ошибку:

migrate -path database/postgres/migrations -database "postgresql://postgres:postgres@localhost:5400/property?sslmode=disable" -verbose up
2022/11/10 18:00:17 error: database driver: unknown driver postgresql (forgotten import?)
make: *** [Makefile:15: migrateup] Error 1

Это файл make, который я использую.

#### IMPORT ENV
include .env
DB_URL=postgresql://$(DB_USER):$(DB_PASSWORD)@$(DB_HOST):$(DB_PORT)/$(DB_NAME)?sslmode=disable

postgres:
    docker run --name postgres -p $(DB_PORT):5432 -e POSTGRES_USER=$(DB_USER) -e POSTGRES_PASSWORD=$(DB_PASSWORD) -d postgres:alpine

createdb:
    docker exec -it postgres createdb --username=$(DB_USER) --owner=$(DB_OWNER) $(DB_NAME)

dropdb:
    docker exec -it postgres dropdb --username=$(DB_USER) $(DB_NAME)

migrateup:
    migrate -path database/postgres/migrations -database "$(DB_URL)" -verbose up

migratedown:
    migrate -path database/postgres/migrations -database $(DB_URL) -verbose down

.PHONY: postgres createdb dropdb

Пожалуйста, помогите мне понять, почему это не работает?

3 ответа

Эта проблема была решена путем удаления golang migrate и повторной установки. После этого это сработало.


0

David Essien
12 Ноя 2022 в 20:27

Сначала вы устанавливаете базу данных драйверов.

Миграция базы данных go install -tags "postgres,mysql" github.com/golang-migrate/migrate/v4/cmd/migrate@latest

Я использую makefile кода

table = $(table)
name = $(name)
url=postgres://postgres:secret@127.0.0.1:5432/school?sslmode=disable
version=$(version)
migration-up :
    migrate -database "$(url)" -path ./migrations/ up $(version)
    
migration-down :
    migrate -database "$(url)" -path ./migrations/ down $(version)
    
migration-create:
    migrate create -ext sql -dir ./migrations/ -seq $(name)

migration-force:
    migrate -database "$(url)" -path ./migrations/ force $(version)

migration-version:
    migrate -database "$(url)" -path ./migrations/ version

make migration-create name=users создать перенос файла

make migration-up version=1 запустить миграцию до запуска файла sql


0

Triadmoko Denny Fatrosa
23 Ноя 2022 в 16:24

Я пытаюсь подключить базу данных MySql с помощью языка Go и выдает следующую ошибку.

sql: unknown driver "mysql" (forgotten import?)

Мой код

package main

    import (
        "database/sql"
        "fmt"
    )

func main() {
    db, err := sql.Open("mysql", "astaxie:[email protected]/test?charset=utf8")
    checkErr(err);
    err=db.Ping();
}

Также, когда я импортирую

        _ "github.com/go-sql-driver/mysql"

Я получаю ошибку

imported and not used

person
Mr x
  
schedule
28.03.2016
  
source
источник


Ответы (3)

Для тех, кто зашел на эту страницу из-за ошибки sql: unknown driver «mysql» (забыли импорт?), пакет database/sql должен использоваться вместе с драйвером базы данных . Это означает, что помимо импорта пакета database/sql, вам необходимо импортировать драйвер базы данных.

Например, для mysql вы можете использовать пакет go-sql-driver. Обычно вы импортируете этот пакет, используя нотацию подчеркивания _, что означает, что он импортируется только из-за его побочных эффектов:

import _ "github.com/go-sql-driver/mysql"

Вы можете узнать больше об этом и найти список драйверов SQL ниже:

  • https://golang.org/pkg/database/sql/
  • https://github.com/golang/go/wiki/SQLDrivers

person
Kyle Chadha
  
schedule
05.05.2017


Попробуйте еще раз, но поищите мои ПРИМЕЧАНИЕ:

package main

import (
    "database/sql"

    _ "github.com/go-sql-driver/mysql"
)
// NOTE - I removed the import for "fmt" because it was unused.

func main() {
    db, err := sql.Open("mysql", "astaxie:[email protected]/test?charset=utf8")
    checkErr(err);
    err=db.Ping();
    // NOTE - the above line will trigger an error because err is unused.
}

Я добавил импорт для драйвера MySQL и удалил «fmt», потому что он не использовался. Это может быть причиной вашей ошибки «импортировано и не используется».

person
Surreal Dreams
  
schedule
28.03.2016

Попробуйте перепроверить расположение пакетов. Я допустил такую ​​ошибку, когда вручную добавил этот пакет в проект. Лучше всего очистить GOROOT и GOPATH из этого пакета и переустановить / повторно подключить его, как указано в источнике: https://github.com/go-sql-driver/mysql

person
Александр Аверьянов
  
schedule
23.09.2018

Понравилась статья? Поделить с друзьями:
  • Error data not accepted from server
  • Error data files corrupt please reinstall application fs 2023
  • Error data files corrupt please reinstall application fs 2019
  • Error data fc2
  • Error data error cyclic redundancy check failed to read data from the file