Git Product home page Git Product logo

go-adodb's Introduction

go-adodb

Microsoft ADODB driver conforming to the built-in database/sql interface

Installation

This package can be installed with the go get command:

go get github.com/mattn/go-adodb

Documentation

API documentation can be found here: http://godoc.org/github.com/mattn/go-adodb

Examples can be found under the ./_example directory

Note

If you met the issue that your apps crash, try to import blank import of runtime/cgo like below.

import (
    ...
    _ "runtime/cgo"
)

License

MIT: http://mattn.mit-license.org/2015

Author

Yasuhiro Matsumoto (a.k.a mattn)

go-adodb's People

Contributors

andybalholm avatar chanchal1987 avatar doun avatar flibustenet avatar mattn avatar mhansen avatar renovate-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-adodb's Issues

How to get VT_VARIANT values from result?

Hi, first of all thanks for all the work you've put into making both this and go-ole.

I need to get data out of a custom proprietary time series database for which an OLEDB driver is supplied. I managed to get things up and running for timestamp and integer parameters, but the driver returns certain values as VT_VARIANT to allow mutiple datatype to be returned in the same column.

For example:
image

Here the value column is of type variant. The resulting object in the interface is of type *ole.VARIANT, but the VT is always empty:

	rows, err := db.Query(queryData)
	if err != nil {
		fmt.Println("select", err)
		return
	}
	defer rows.Close()

	fmt.Println(rows.Columns())
	ct, _ := rows.ColumnTypes()
	fmt.Println(ct[0].Name(), ct[0].DatabaseTypeName(), ct[0].ScanType())

	for rows.Next() {
		var timestamp time.Time
		var value interface{}
		err = rows.Scan(&timestamp, &value)
		if err != nil {
			fmt.Println("scan", err)
			return
		}
		fmt.Println(timestamp, value)
	}
2018-04-27 13:37:28 +0200 CEST &{VT_EMPTY 0 0 0 131693095766368559 [0 0 0 0 0 0 0 0]}
2018-04-27 13:42:04 +0200 CEST &{VT_EMPTY 0 0 0 131693100061366196 [0 0 0 0 0 0 0 0]}
2018-04-27 13:44:35 +0200 CEST &{VT_EMPTY 0 0 0 131693100061341924 [0 0 0 0 0 0 0 0]}
2018-04-27 13:45:07 +0200 CEST &{VT_EMPTY 0 0 0 131693100061317651 [0 0 0 0 0 0 0 0]}
2018-04-27 13:45:39 +0200 CEST &{VT_EMPTY 0 0 0 131693104356260674 [0 0 0 0 0 0 0 0]}
2018-04-27 14:09:17 +0200 CEST &{VT_EMPTY 0 0 0 131693117241186835 [0 0 0 0 0 0 0 0]}
2018-04-27 14:10:18 +0200 CEST &{VT_EMPTY 0 0 0 131693117241211108 [0 0 0 0 0 0 0 0]}
2018-04-27 14:12:51 +0200 CEST &{VT_EMPTY 0 0 0 131693117241186835 [0 0 0 0 0 0 0 0]}
2018-04-27 14:14:48 +0200 CEST &{VT_EMPTY 0 0 0 131693121536178404 [0 0 0 0 0 0 0 0]}
2018-04-27 14:23:38 +0200 CEST &{VT_EMPTY 0 0 0 131693125831121427 [0 0 0 0 0 0 0 0]}
2018-04-27 14:24:12 +0200 CEST &{VT_EMPTY 0 0 0 131693125831097154 [0 0 0 0 0 0 0 0]}
2018-04-27 14:24:58 +0200 CEST &{VT_EMPTY 0 0 0 131693125831066814 [0 0 0 0 0 0 0 0]}
2018-04-27 14:30:48 +0200 CEST &{VT_EMPTY 0 0 0 131693130126058382 [0 0 0 0 0 0 0 0]}

How should I handle this type of column?

Any ideas are much appreciated, spent almost a full day I trying different things 😞 Thanks in advance!!!

Table query always returns an error on mssql2000/2005

package main

import (
"database/sql"
"flag"
"fmt"
"log"
_ "github.com/mattn/go-adodb"
_ "runtime/cgo"
)

var (
isLocalAuth bool
isMssql2000 bool
remoteServerIP string
instance string
)

func init() {
flag.BoolVar(&isLocalAuth, "local", false, "true windows,false sa.")
flag.BoolVar(&isMssql2000, "mssql2000", false, "is it MSSQL2000?")
flag.StringVar(&remoteServerIP, "ip", "192.168.1.87", "set server remote ip.")
flag.StringVar(&instance, "instance", "MSSQLSERVER", "set instance.")
}

type Mssql struct {
*sql.DB
dataSource string
database string
windows bool
sa *SA
}

type SA struct {
user string
password string
port int
}

func NewMssql() *Mssql {
mssql := new(Mssql)
source := "localhost"
if !isLocalAuth {
if instance == "MSSQLSERVER" {
source = fmt.Sprintf("%s", remoteServerIP)
} else {
source = fmt.Sprintf("%s\%s", remoteServerIP, instance)
}
}
mssql = &Mssql{
dataSource: source,
database: "suilang",
windows: isLocalAuth,
sa: &SA {
user: "sa",
password: "lcs6718",
port: 1433,
},
}

return mssql

}

func (ms *Mssql) Open() error {
config := fmt.Sprintf("Provider=SQLOLEDB;Initial Catalog=%s;Data Source=%s", ms.database, ms.dataSource)
if ms.windows {
config = fmt.Sprintf("%s;Integrated Security=SSPI", config)
} else {
if isMssql2000 {
config = fmt.Sprintf("%s,%d;user id=%s;password=%s", config, ms.sa.port, ms.sa.user, ms.sa.password)
} else {
config = fmt.Sprintf("%s;user id=%s;password=%s", config, ms.sa.user, ms.sa.password)
}
}

var err error
ms.DB, err = sql.Open("adodb", config)
fmt.Println(config)
return err

}

func (ms *Mssql) Select() {
rows, err := ms.Query("select * from users")
if err != nil {
fmt.Println("select error:")
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var uid, name string
if err := rows.Scan(&uid, &name); err != nil {
log.Fatal(err)
fmt.Println("columns error.")
}
log.Printf("uid %s name is %s\n", uid, name)
}
}

func main() {
flag.Parse()
mssql := NewMssql()
defer mssql.Close()
err := mssql.Open()
if err != nil {
fmt.Println("sql open error: ", err)
return
}
mssql.Select()
}

Running the above code on mssql2000 and 2005 always returns an error when querying data, just like
select error:
2019/03/30 22:48:09
exit status 1

go version go1.11.5 linux/amd64

do not support RowsNextResultSet

// RowsNextResultSet extends the Rows interface by providing a way to signal
// the driver to advance to the next result set.
type RowsNextResultSet interface {
Rows

// HasNextResultSet is called at the end of the current result set and
// reports whether there is another result set after the current one.
HasNextResultSet() bool

// NextResultSet advances the driver to the next result set even
// if there are remaining rows in the current result set.
//
// NextResultSet should return io.EOF when there are no more result sets.
NextResultSet() error

}

read/write a "Memo" field in Access(.mdb)

With a [ ]byte type, we can read its value from a memo field. But we can not write it back. (Code is a memo field)
sqlstr = "SELECT Code FROM Texts"
rows, err = dbsrc.Query(sqlstr)
defer rows.Close()
if err != nil {
fmt.Println("select", err) }
for rows.Next() {
var Code [] byte
err = rows.Scan(&Code)
_, err = db.Exec("insert into Texts ( Code) values (?)", Code) }

GUID datetime INSERT

id is GUID uniqueidentifier
[receivetime], [completetime] is datetime

INSERT INTO [topic]([id],[receivetime], [completetime])
VALUES ('03fc4c83-dae6-4273-aae9-fb50c30248ab','2015-01-27 19:56:42.798', '2015-01-27 19:56:45.792')
successful!!!!

s, err := models.Db.Prepare(“INSERT INTO [topic]([id],[receivetime], [completetime])
VALUES (?,?,?)”)

s.Exec(id,receivetime,completetime)

failure???

Error while creating MDB file with provided example

I just tried with the sample code provided in mdb.go but getting empty error message. Any help?
Below is the code to test.

package main

import (
"database/sql"
"fmt"
"os"
_ "runtime/cgo"
"time"

"github.com/go-ole/go-ole"
"github.com/go-ole/go-ole/oleutil"
_ "github.com/mattn/go-adodb"

)

var provider string

func createMdb(f string) error {
unk, err := oleutil.CreateObject("ADOX.Catalog")
if err != nil {
fmt.Println(err)
return err
}
defer unk.Release()
cat, err := unk.QueryInterface(ole.IID_IDispatch)
if err != nil {
fmt.Println("2")
return err
}
defer cat.Release()
provider = "Microsoft.Jet.OLEDB.4.0"
r, err := oleutil.CallMethod(cat, "Create", "Provider="+provider+";Data Source="+f+";")
if err != nil {
provider = "Microsoft.ACE.OLEDB.12.0"
r, err = oleutil.CallMethod(cat, "Create", "Provider="+provider+";Data Source="+f+";")
if err != nil {
fmt.Println("3")
return err
}
}
r.Clear()
return nil
}

func main() {
ole.CoInitialize(0)
defer ole.CoUninitialize()

f := "./example.mdb"

os.Remove(f)

err := createMdb(f)
if err != nil {
	fmt.Println("create mdb", err)
	return
}

}

db.Query error with vfpoledb connection

I get the following error when I want make parametric sql query after connecting the Vfp database
// The Error Message : "select sql: statement expects 0 inputs; got 1"

The error occurs at this line
rows, err := db.Query("select id, name, created from foo where id=?", 1)

Similarly the same error (select sql: statement expects 0 inputs; got 3) take place following line

stmt, err := tx.Prepare("insert into foo (id, name, created) values (?, ?, ?)")
...
_, err = stmt.Exec(i, "Test", time.Now())

The driver is I use Microsoft OLE DB Provider for Visual FoxPro 9.0 :
http://www.microsoft.com/en-us/download/details.aspx?id=14839

Returns corrupt value when the data type is decimal or money in database(MS SQL Server 2005)

Testing database: MS SQL Server 2005
Table schema:
create table Test(
    ID int,
    Amount decimal(9,2)
)
Prepare data:
insert Test(ID, Amount)
Values(1, 1.5)

insert Test(ID, Amount)
Values(1, 9.30)
Go code
package main

import (
    "database/sql"
   "fmt"
    _ "github.com/mattn/go-adodb"
   )

func main() {
    db, err := sql.Open("adodb", "connection string")
    if err != nil {
        log.Printf("Can't open database as error: %s", err)
    } else {
        fmt.Println("Connected database")
    }

    sql := "select ID, Amount from Test"
    rows, err := db.Query(sql)
    checkError(err)

    for rows.Next() {
        var id int
        var money float64
        err = rows.Scan(&id, &money)
        checkError(err)
        fmt.Println("ID: "id, " Amount: ", money)
    }
}

func checkError(err error) {
    if err != nil {
        log.Println(err)
    }
}
Testing result:
ID:  1  Amount:  150
ID:  1  Amount:  930

If I alter data type decimal to money, will get error as below

 2013/01/17 15:49:50 sql: Scan error on column index 1: converting string "<nil>"
 to a float64: strconv.ParseFloat: parsing "<nil>": invalid syntax
ID:  1  Amount:  0
2013/01/17 15:49:50 sql: Scan error on column index 1: converting string "<nil>"
to a float64: strconv.ParseFloat: parsing "<nil>": invalid syntax
ID:  1  Amount:  0
2013/01/17 15:49:50 sql: Scan error on column index 1: converting string "<nil>"
to a float64: strconv.ParseFloat: parsing "<nil>": invalid syntax

Querying Windows search DB fails with "Current provider does not support commands with parameters."

Hello,
I'm trying to port some of my PowerShell code to Go, and I'm stumbling here when porting the interface to the search index on Windows. With PowerShell it's simply case of connecting System.Data.OleDb.OleDbCommand to provider "provider=search.collatordso;extended properties=’application=windows’;" and then running a simple SQL command like "SELECT Top 5 System.ItemPathDisplay FROM SYSTEMINDEX" (can get more complex with WHERE clauses).

I made a simple script:

package main

import (
	"database/sql"
	"fmt"
	"log"
	_ "github.com/mattn/go-adodb"
)

var provider = `provider=search.collatordso;extended properties="application=windows";`

func main() {
	fmt.Println(sql.Drivers())
	db, err := sql.Open("adodb", provider)
	if err != nil {
		log.Fatalln("open", err)
	}
	defer db.Close()

	fmt.Println("Pong:", db.Ping())
	fmt.Println("Stats:", db.Stats())

	rows, err := db.Query("SELECT Top 5 System.ItemPathDisplay FROM SYSTEMINDEX")
	if err != nil {
		log.Fatalln("select", err)
	}
	defer rows.Close()
}

and when I run it I get:

[adodb]
Pong: <nil>
Stats: {0 1 0 1 0 0s 1 0}
2019/06/03 17:09:48 select Exception occurred. (Current provider does not support commands with parameters.)
exit status 1

Please help with any suggestions, I'm at my wits' end.

can't get first one line

In my sql server has three lines data, but throw sql server only get two data. Can't get first one line

package main

import (
"fmt"
_ "github.com/mattn/go-adodb"
"database/sql"
)
func main() {
db, err := sql.Open("adodb", "Provider=SQLOLEDB;Initial Catalog=test;Data Source=SH-XIEMENGJUN\\SQLEXPRESS;user id=sa;password=123456")

if err != nil {
    panic(err)
}
rows, err := db.Query("select uid, username from userinfo")
if err != nil {
    fmt.Println(err)
    return
}
defer rows.Close()

for rows.Next() {
    var id int
    var name string
    rows.Scan(&id, &name)
    println(id, name)
}
}

utf16 error

run examples Fail (windows7 x64 )

throw: markallocated: bad pointer

goroutine 1 [running]:
unicode/utf16.Encode(0xf840037a40, 0x500000005, 0xf840037a40, 0x500000005, 0x1, ...)
 C:/Users/ADMINI1/AppData/Local/Temp/2/bindist119677522/go/src/pkg/unicode/utf16/utf16.go:64 +0x7f
syscall.StringToUTF16(0x4d48ac, 0x100000004, 0x2a1a30, 0x0, 0x40f49e, ...)
 C:/Users/ADMINI1/AppData/Local/Temp/2/bindist119677522/go/src/pkg/syscall/syscall_windows.go:57 +0x6f
syscall.StringToUTF16Ptr(0x4d48ac, 0x4, 0x1, 0xf84004c8e0, 0x100000001, ...)
 C:/Users/ADMINI1/AppData/Local/Temp/2/bindist119677522/go/src/pkg/syscall/syscall_windows.go:73 +0x32
github.com/mattn/go-ole.getIDsOfName(0x52dc888, 0x2a1b30, 0x100000001, 0x0, 0x0, ...)
 C:/Go/src/pkg/github.com/mattn/go-ole/ole.go:622 +0xd3
github.com/mattn/go-ole.(_IDispatch).GetIDsOfName(0x52dc888, 0x2a1b30, 0x100000001, 0x0, 0x0, ...)
 C:/Go/src/pkg/github.com/mattn/go-ole/ole.go:196 +0x73
github.com/mattn/go-ole/oleutil.CallMethod(0x52dc888, 0x4d48ac, 0x6d65744900000004, 0x2a1cd8, 0x100000001, ...)
 C:/Go/src/pkg/github.com/mattn/go-ole/oleutil/oleutil.go:46 +0xc1
github.com/mattn/go-adodb.(_AdodbRows).Next(0xf8400563f0, 0xf8400378a0, 0x200000002, 0x0, 0x0, ...)
 C:/Go/src/pkg/github.com/mattn/go-adodb/adodb.go:291 +0x44d
database/sql.(*Rows).Next(0xf84002f2a0, 0x4e43f4, 0x656c657300000018, 0x0)
 C:/Users/ADMINI1/AppData/Local/Temp/2/bindist119677522/go/src/pkg/database/sql/sql.go:912 +0x103
main.main()
 D:/My Design/go/src/testdb/main.go:58 +0x889

goroutine 2 [syscall]:
created by runtime.main
 C:/Users/ADMINI~1/AppData/Local/Temp/2/bindist119677522/go/src/pkg/runtime/proc.c:221
> exit code 2, process exited normally.

db.Query breaks the application over ab benchmark

I have divided the mdb.go example in two apps:

When I test the mdb2 app manually with the browser, curl, etc it works fine, but when y put them on load, for example:

ab -n 100 -c 10 -k http://app.url/

ab exits with "...apr_socket_recv: Connection reset by peer (54)", and the app crashes with:

Exception 0xc00000fd 0x0 0x3150263c
PC=0x31e4d284fr French

signal arrived during cgo execution

syscall.Syscall9(0x4bcc6bd6, 0x9, 0x315922a0, 0x5, 0x6d65f0, ...de German
)
es Spanish
        /usr/local/go/src/pkg/runtime/zsyscall_windows_windows_386.c:123 +0x49
github.com/mattn/go-ole.invoke(0x315922a0, 0x5, 0x1, 0x0, 0x0, ...)
        /Users/pmd/Dropbox/Code/go/src/github.com/mattn/go-ole/idispatch.go

I have test it wit wrk with similar errors:

wrk -t2 -c10 -d5s http://app.url

Thanks.

cgo import ?

In go-ole we can read that it doesn't use cgo.
I wonder if go-adodb still need cgo and a c compiler on windows ?
I'm worried with the "issue that your apps crash", what does it mean ? Could the readme be more precise about this ?
Thanks

get two field from MSSQL by db.Query will get the same field sometimes.

In sqlserver2008, as the code sample below, I select "name""name1" from the test table, if the "name1" is NULL, the "name1" value will be the same as "name"

// the code sample
func testDB(db *sql.DB) {
    db.Exec("if object_id(N'test',N'U') is not null drop table test")
    db.Exec("create table test(id int not null primary key, name varchar(20), name1 varchar(20) )")
    for i := 0; i < 4; i++ {
        name := "name" + strconv.Itoa(i)
        name1 := strconv.Itoa(i)
        if i%2 == 1 {
            db.Exec("insert into test(id, name, name1) values(?, ?, ?)", i, name, name1)
        } else {
            db.Exec("insert into test(id, name) values(?, ?)", i, name)
        }
    }

    rows, _ := db.Query("select * from test")
    for rows.Next() {
        var id int
        var name, name1 string
        rows.Scan(&id, &name, &name1)
        log.Printf("result: %d, %s, %s ", id, name, name1)
    }
}

Could not able to get column definitions from accdb

I have tried below code to get column definition from a ms-access database, but all are giving default values except the name.

	coltype, err := rows.ColumnTypes()
	for _, col := range coltype {
		len, _ := col.Length()
		pre, scl, _ := col.DecimalSize()
		nullable, _ := col.Nullable()
		fmt.Println(col.Name(), col.DatabaseTypeName(), len, pre, scl, nullable)
	}

"class not registered" error

Hi mattn or anyone else reading,

With example mdb.go file. It compiles okay into an exe, when i run it, it gives:

create mdb Exception occurred. (Class not registered)

It was having trouble with
oleutil.CallMethod(cat, "Create", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+f+";")

So maybe i need to modify that to an alternative. Can anyone point me in the right direction?
So far it looks as though i need to be running the 32bit version of Go, or install 64bit version of Office, but i'm hoping to not do that.

Many thanks.

sql: expected 0 arguments, got 173

Hello, I am trying to insert some records into an Access database (MDB format)

I have a fixed string that I am using as insert statement and then I provide the 173 parameters in the params slice

insertStmt is a StringBuilder and destDb is a *sqlx.Db

res, err := destDb.Exec(insertStmt.String(), params...) log.Println(res)

Unfortunately I have not been able to run the command, it looks like the library does not understand I want 173 parameters passed with the question mark placeholder

INSERT INTO ARCHIVIO ([Codice],[Tel],[Data],[ATTIVA],[RagSoc],[Sede],[Cap1],[Città1],[Pr1],[DomFis],[Cap2],[Città2],[Pr2],[CON FIS],[COD FIS],[P IVA],[COD ATT],[NAT GIUR],[DATA COST],[DATA CESS],[REG IMP],[REA],[AIA],[REC],[MECC EXP],[INAIL],[INPS],[CAPE],[AUT APPREN],[CAP SOC],[SOGG 626],[RESPONSABILE],[USSL],[UFF IMPOSTE],[BANCA CLI],[C/C],[MOD P],[BANCA PRAGMA],[SOCIO1],[CF1],[QUOTA1],[NATOA1],[IL1],[LAV1 SI/NO],[RES1],[CP1],[CITT1],[PRO1],[SOCIO2],[CF2],[QUOTA2],[NATOA2],[IL2],[LAV2 SI/NO],[RES2],[CP2],[CITT2],[PRO2],[SOCIO3],[CF3],[QUOTA3],[NATOA3],[IL3],[LAV3 SI/NO],[RES3],[CP3],[CITT3],[PRO3],[SOCIO4],[CF4],[QUOTA4],[NATOA4],[IL4],[LAV4 SI/NO],[RES4],[CP4],[CITT4],[PR4],[SOCIO5],[CF5],[QUOTA5],[NATOA5],[IL5],[LAV5 SI/NO],[RES5],[CP5],[CITT5],[PR5],[LEGALE RAPPRESENT],[POTERI FIRMA],[OGGETTO],[NOTE],[NOTE1],[NOTE2],[NOTE3],[IMU],[DR],[770],[PAGHE],[PAGHE LIGHT],[CONTRATTO],[DATA FATTURA],[IMPORTO FATTURA],[VALUTA BONIFICO],[SOCIETA' ASSITENTE],[RAPPRES LAVORATORI],[MEDICO COMPETENTE],[SERVIZIO PREVENZIONE],[CONAI],[MAIL],[MAIL CERTIFICATA],[CELLULARE],[PERSONA RIFERIMENTO],[UTENTE ID PL],[PASSWORD PL],[FAX],[REGIONE],[STUDIO COLLEGATO],[SCADENZA CONTRATTO],[RESPONSABILE CED],[CED ENTRO IL],[DIP],[CONTABILITA'],[CONSUL CONTAB],[CONTABILITA LIGHT],[CONTABILITA SEMPL],[CONTABILITA ORDIN],[RESPONSABILE CONTABILITA],[IMPORTO SEMPL MENSILE],[IMPORTO ORDIN MENSILE],[IMPORTO CED PAGA],[CANONE ANNUO CIRCOLAR],[ISCRIZIONE ENTI],[UNILAV ASS CESS TRASF],[UNILAV PARTICOLARI],[ISCRIZ ENTI BILATERALI],[CESSAZIONE POS ENTI],[DENUNCIA CIG A DIP],[DENUNCIA INFORTUNIO],[CONTRATTI A PROGETTO],[RICHIESTA DURC],[F24 A RATA],[F24 COMPENSAZ EXTRA PAGHE],[CALCOLO NETTO LORDO DIP],[RAVVEDIMENTO OPEROSO],[INSERIMENTO 730],[INSERIMENTO ASS FAMILIARI],[DICHIARAZIONE UFFICIO MIRATO],[CONSUL EXTRA ELAB IMP OR],[PRES DICH SALARI INAIL],[IMPORTO CUD],[CON SEMPL ANNUALE],[CON ORDIN ANNUALE],[PRES E MENS],[ASSUNZIONI DIMISSIONI],[TIROCINIO ISTRUTTORIA ED ASUNZIONE],[LETTERE COMUNICAZIONI PARTICOLARI],[ALTRI PATTI],[STUDIO DI FATTURAZIONE],[Cod esportazione movimenti],[Codice cliente Parce],[INSEGNA],[UL],[FATT AUT PL],[FATTAUT CL],[DATA FINE SERVIZI],[UNI],[SCADENZA FIRMA DIGITALE],[FIRMA1],[FIRMA2],[FIRMA3],[FIRMA4],[FIRMA5]) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)

go run csv.go have an error, err is empty but is not nil

@mattn I am go run csv.go have an error.
development environment:macOS10.12.6 + go1.9.2

package main

import (
	"fmt"
	"database/sql"
	_ "github.com/mattn/go-adodb"
	"os"
)

func main() {
	os.Remove("example.csv")

	db, err := sql.Open("adodb", `Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.;Extended Properties="Text;HDR=NO;FMT=Delimited"`)
	if err != nil {
		fmt.Println(err)
		return
	}

	_, err = db.Exec("create table example.csv(f1 text, f2 text, f3 text)")
	if err != nil {   **_// The err is empty but is not nil_** 
		fmt.Println(err)  
		return
	}
    ......
}

Possible incombatibility with current go-ole

Thank you for your project. It is the first time I tried to code in Go.

I observed initially in adodb.go that was a reference
"github.com/mattn/go-ole" and I changed the import to to github.com/go-ole/go-ole because of many
compiling errors with your github.com/mattn/go-ole[/oleutils etc etc]

But then I had is

c:/prog/go/bin/go.exe build -i [C:/Prog/GOPATH/src/github.com/mattn/go-adodb]

github.com/mattn/go-adodb

.\adodb.go:355: invalid slice index sa.Bounds (type [16]byte)
.\adodb.go:391: invalid slice index sa.Bounds (type [16]byte)
Error: process exited with code 2.

It was mentioning the line
dest[i] = (*[1 << 30]byte)(unsafe.Pointer(uintptr(sa.Data)))[0:sa.Bounds.Elements]
^

I had a look into the safearray.go and I saw
////////////////////////////////////////////////////////
// Package is meant to retrieve and process safe array data returned from COM.

package ole

// SafeArrayBound defines the SafeArray boundaries.
type SafeArrayBound struct {
Elements uint32
LowerBound int32
}

// SafeArray is how COM handles arrays.
type SafeArray struct {
Dimensions uint16
FeaturesFlag uint16
ElementsSize uint32
LocksAmount uint32
Data uint32
Bounds [16]byte
}

// SAFEARRAY is obsolete, exists for backwards compatibility.
// Use SafeArray
type SAFEARRAY SafeArray

// SAFEARRAYBOUND is obsolete, exists for backwards compatibility.
// Use SafeArrayBound
type SAFEARRAYBOUND SafeArrayBound


Bounds was a byte array but not a struct to have an element as a member of it.

Excuse my COM and GO ignorance.
Can you help with this?

Thank you for your very good job, MattN!

Memory error when using OLE object column

I get a panic when trying to read an OLE object from a DB.

The program fails the first time it calls rows.Next()

I have attached a database to work with the following code:

crash.zip

package main

import (
	"database/sql"
	"fmt"

	"github.com/go-ole/go-ole"
	_ "github.com/mattn/go-adodb"
)

func main() {
	ole.CoInitialize(0)
	defer ole.CoUninitialize()

	db, err := sql.Open("adodb", "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=crash.mdb;")
	if err != nil {
		fmt.Println("open", err)
		return
	}
	defer db.Close()

	rows, err := db.Query("select * from Table1")
	if err != nil {
		fmt.Println("select", err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		// Will never get here
	}
}
```

(Class not register) Provider cannot be found. It may not be properly installed. "發生例外狀況。 (找不到提供者。它可能未被正確安裝。)"

with the mdb.go example it shows the following error message

create mdb 發生例外狀況。 (類別未登錄)
> Class not registered

this playground shows another message but it has the same meaning.

"發生例外狀況。 (找不到提供者。它可能未被正確安裝。)"
>  Provider cannot be found. It may not be properly installed.

image

Query in HTTP Handler fails on 2nd request.

This reminds me a little bit of issue: #14

I've tried to reduce my code to the simplest form that can reproduce the problem. If I take my normal code to query a MS Access database and put it in an HttpHandler, it will always fail on the 2nd request to that path with "signal arrived during cgo execution". I can wait a minute or more between the 1st request (which will work) and the 2nd request (which will fail). I can also use a browser, curl, or wget to get the same results.

Yet I can call it repeatedly if I don't use it in a HttpHandler. I wonder if it has something to do with the http handler creating go routines?

I have GOARCH=386 as well, since I can't seem to make any queries work with Access unless I set that.

At this point, I've spent about a day of time trying various things and I'm running out of ideas.

    import (
        "database/sql"
        "fmt"
        _ "github.com/mattn/go-adodb"
        "net/http"
        "sync"
    )

    var mutex sync.Mutex

    func trendHandler(w http.ResponseWriter, r *http.Request) {
        mutex.Lock()
        defer mutex.Unlock()

        path := `C:\Alarm Frequency Report\BACtalk.mdb`
        connString := "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";"
        db, err := sql.Open("adodb", connString)
        if err != nil {
            fmt.Println("Open", err)
            return
        }
        defer db.Close()

        rows, err := db.Query("SELECT devinst FROM tblAlarmHistory")
        if err != nil {
            fmt.Println("Query", err)
        }
        defer rows.Close()

        for rows.Next() {
            var id int
            rows.Scan(&id)
            fmt.Println(id)
        }
    }

    func main() {
        http.HandleFunc("/", trendHandler)
        http.ListenAndServe(":8080", nil)

        // 2nd request to url above always causes an error.
        // but, if you comment above and uncomment below
        // you can query to your hearts content.

        // for i := 0; i < 1000; i++ {
        //  trendHandler(nil, nil)
        // }
    }

List of tables and fields

Hi,

I'm looking for a way to extract tables and fields of a MSAccess database without making query. I wonder if go-adodb can help me for that or if i should look at go-ole ? (i'm not very confortable with windows api)
Maybe there is an example for this ?

Thanks

Fail to install Walk for Go

Does walk fo go only work well in Windows?My OS is Mac, I can't install walk and the errors is showed behind.

$ go get github.com/lxn/walk

github.com/lxn/go-winapi

Documents/Go/mypkg/src/github.com/lxn/go-winapi/advapi32.go:80: too many arguments in call to syscall.Syscall
Documents/Go/mypkg/src/github.com/lxn/go-winapi/advapi32.go:93: too many arguments in call to syscall.Syscall6
Documents/Go/mypkg/src/github.com/lxn/go-winapi/advapi32.go:105: too many arguments in call to syscall.Syscall6
Documents/Go/mypkg/src/github.com/lxn/go-winapi/advapi32.go:112: undefined: syscall.Syscall9
Documents/Go/mypkg/src/github.com/lxn/go-winapi/advapi32.go:131: too many arguments in call to syscall.Syscall6
Documents/Go/mypkg/src/github.com/lxn/go-winapi/comctl32.go:206: too many arguments in call to syscall.Syscall
Documents/Go/mypkg/src/github.com/lxn/go-winapi/comctl32.go:215: too many arguments in call to syscall.Syscall
Documents/Go/mypkg/src/github.com/lxn/go-winapi/comctl32.go:227: too many arguments in call to syscall.Syscall6
Documents/Go/mypkg/src/github.com/lxn/go-winapi/comctl32.go:235: too many arguments in call to syscall.Syscall
Documents/Go/mypkg/src/github.com/lxn/go-winapi/comctl32.go:245: too many arguments in call to syscall.Syscall
Documents/Go/mypkg/src/github.com/lxn/go-winapi/comctl32.go:245: too many errors

go get / build fails

C:\Users\Alex>go get -u github.com/mattn/go-adodb

github.com/mattn/go-adodb

C:\devel\go\thirdparty\src\github.com\mattn\go-adodb\adodb.go:347: sa.PvData und
efined (type *ole.SAFEARRAY has no field or method PvData)
C:\devel\go\thirdparty\src\github.com\mattn\go-adodb\adodb.go:347: sa.RgsaBound
undefined (type *ole.SAFEARRAY has no field or method RgsaBound)
C:\devel\go\thirdparty\src\github.com\mattn\go-adodb\adodb.go:377: sa.PvData und
efined (type *ole.SAFEARRAY has no field or method PvData)
C:\devel\go\thirdparty\src\github.com\mattn\go-adodb\adodb.go:377: sa.RgsaBound
undefined (type *ole.SAFEARRAY has no field or method RgsaBound)

MSSQL 2000,2012 Datetime result not same in db datetime

i found a bug, time result not same in go-adodb and real datetime in db, i'm using mssql 2000,2012 and go1.9.1 windows/386
example query :
SELECT GETDATE() AS tgl
result :
2018-10-05 13:57:54.907

code


    rows, err := DB.Query("SELECT  GETDATE() AS tgl")
	if err != nil {
		fmt.Printf("select query err: %s/n", err)
	}
	for rows.Next() {
		var dt time.Time

		rows.Scan(&dt)
		 
		println(b.String())
		
	}

result in go-adodb :
2018-10-05 13:53:28 +0700 +07

need result :
2018-10-05 13:57:54.907 +0700 +07

WinCC OLE DB Provider error executing query

So i have been trying to implement this module to access a database which using WinCC OLE DB Provider(Page 22 to 25). I can connect to the database using open method and i also successfully ping the database, but when i execute the query it returns error.

here's the query.

TAG:R,'SystemArchive\\1511_AT_1379A/MS.PV_Out#Value','2022-02-08 07:35:00.000', '2022-02-08 07:40:00.000'

and here's the error log from the program i made.

Test Connection String : Provider=WinCCOLEDBProvider.1;Persist Security Info=False;User ID="";Data Source=10.1.1.1\WINCC;Catalog=CC_OS_1__21_12_14_16_25_11R;Mode=Read;Location="";Mode=Read;Extended Properties=""

Sql Driver : [adodb]

Ping Successful!

Test Query : TAG:R,'SystemArchive\1511_AT_1379A/MS.PV_Out#Value','2022-02-08 07:35:00.000', '2022-02-08 07:40:00.000'
Error Preparing Statement Exception occurred. (Provider cannot derive parameter information and SetParameterInfo has not been called.)

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x1 addr=0x38 pc=0x864d82]

goroutine 1 [running]:
database/sql.(*Stmt).QueryContext(0x0, {0x8de310, 0xc00009e010}, {0x0, 0x0, 0x0})
C:/Program Files/Go/src/database/sql/sql.go:2726 +0x82
database/sql.(*Stmt).Query(...)
C:/Program Files/Go/src/database/sql/sql.go:2784
main.main()
D:/tugas/Pagawean/MusaGreen/Repo/adodb-wincc-oledb/main.go:63 +0x45f

The point i take here is the provider cannot derive parameter information and the set parameter info has not been called. I have been trying to search across webs but i still havent managed to figure what the error exactly means and what the provider actually wants. Most cases i found is about the provider version x86 vs x64, which people prefer to use x86 and there is another one saying the error occured because of the provider bug so it needs to set the cursor within "ADODB.Connection" object. I have tried the second one by forking this repo and modify the Open() method by adding this line

_, err = oleutil.PutProperty(db, "CursorLocation", 3)
if err != nil {
	return nil, err
}
val, err := oleutil.GetProperty(db, "Parameters")
if err != nil {
	return nil, err
}
dbrc := val.ToIDispatch()
val.Clear()

then i return the dbrc on return &AdodbConn{db: dbrc}, nil.

Still no luck this far, is there anyone can point something out? is there anything i miss here?
kind regard thank you :)

DateTime Fields Always return "2118-03-XX XX:XX:XX.XXXXXXXXXXXX UTC"

The code is as following:

============================
for rows.Next() {
        var date time.Time
        rows.Scan(&date)
        fmt.Println(date)
    }
============================

The Result is as followiing:

2118-03-04 04:28:28.545076635 +0000 UTC

2118-03-04 04:28:28.381231586 +0000 UTC

2118-03-04 04:28:27.996275258 +0000 UTC

2118-03-04 04:28:27.826067295 +0000 UTC

2118-03-04 04:28:27.340895064 +0000 UTC

2118-03-04 04:28:27.242269889 +0000 UTC

2118-03-04 04:28:27.041838082 +0000 UTC

2118-03-04 04:28:26.865267204 +0000 UTC

2118-03-04 04:28:26.209887009 +0000 UTC

2118-03-04 04:28:25.976049901 +0000 UTC

But in fact ,the Datas in My Database(MSQL2000 or MSSQL2008) are :

2011-02-14 21:25:46.000
2011-02-14 21:24:03.000
2011-02-14 21:20:01.000
2011-02-14 21:18:14.000
2011-02-14 21:13:09.000
2011-02-14 21:12:07.000
2011-02-14 21:10:01.000
2011-02-14 21:08:10.000
2011-02-14 21:01:18.000
2011-02-14 20:58:51.000

Would Please tell me WHY? or What should I do to correct the errors?
Thank You.

multithread error and suggest (SQL Server 2k)

Hello,Mattn.
When I using go-adodb connecting the SQL Server 2000 with several connections,errors occured as"CoInitialize has not been called".

So I have to modify the code adodb.go:

  1. remove ole.CoInitialize(0) from init()
  2. add ole.CoInitialize(0) to func (d *AdodbDriver) Open(dsn string) (driver.Conn, error)
  3. add ole.CoUninitialize() to func (c *AdodbConn) Close() error

At last,sorry for my poor English ,and hope to be helpful!!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.