jdbc和golang操作数据库

阙繁
2023-12-01

java

依赖

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.23.jre7</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>9.2.1.jre8</version>
        </dependency>
        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>21.1.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.ibm.db2.jcc</groupId>
            <artifactId>db2jcc</artifactId>
            <version>db2jcc4</version>
        </dependency>

驱动相关

//mysql
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/test";
//oracle
Class.forName("oracle.jdbc.driver.OracleDriver");
url = "jdbc:oracle:thin:@127.0.0.1:1521/test";
//pgsql
Class.forName("org.postgresql.Driver");
url = "jdbc:postgresql://127.0.0.1:5432/test";
//mssql
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
url = "jdbc:sqlserver://127.0.0.1:1433;databaseName=test;";
//db2
Class.forName("com.ibm.db2.jcc.DB2Driver");
url = "jdbc:db2://127.0.0.1:50000/test";

低版本兼容性需要注意:driver和url需要变动,如sqlserver,mysql等

golang

依赖,建议module管理

    //odbc
	_ "github.com/alexbrainman/odbc"
	//mssql
	_ "github.com/denisenkom/go-mssqldb"
	//mysql
	_ "github.com/go-sql-driver/mysql"
	//oracle
	_ "github.com/godror/godror"

	// _ "github.com/ibmdb/go_ibm_db"
	//pgsql
	_ "github.com/jackc/pgx/v4/stdlib"

db2使用的是odbc,go_ibm_db包需要指定CGO_FLAGS,如此执行testing会有dlv的问题
驱动相关

switch conf.DbType {
	case Mysql:
	     url:="userName:password@tcp(127.0.0.1:3306)/test?charset=utf8"
	     db, err = sql.Open("mysql", url)
	case Oracle:
		url := `user="a" password="b" connectString="127.0.0.1:1521/test"`
		db, err = sql.Open("godror", url)
	case Mssql:
		url := `sqlserver://name:pwd@127.0.0.1:1433?database=test`
		db, err = sql.Open("sqlserver", url)
	case Pgsql:
		url := `postgres://name:pwd@127.0.0.1:5432/test?sslmode=disable`
		db, err = sql.Open("pgx", url)
	case Db2:
		url := `DSN=133DB2;uid=userName;pwd=passwd`
		db, err = sql.Open("odbc", url)
	}

db2的odbc客户端环境搭建

 类似资料: