Sachith Muhandiram
Sachith Muhandiram

Reputation: 2972

Check if database table exists using golang

I am trying to do a simple thing, check if there is a table, if not then create that table in database.

Here this is the logic I used.

    test := "June_2019"
    sql_query := `select * from ` + test + `;`

    read_err := db.QueryRow(sql_query, 5)
    error_returned := read_err.Scan(read_err)
    defer db.Close()

    if error_returned == nil {
        fmt.Println("table is there")

    } else {
        fmt.Println("table not there")
    }

In my database I have June_2019 table. But still this code returns me not nil value. I used db.QueryRow(sql_query, 5) 5 as I have five colomns in my table.

What am I missing here? I am still learning golang.

Thanks in advance.

Upvotes: 3

Views: 10090

Answers (1)

Sachith Muhandiram
Sachith Muhandiram

Reputation: 2972

I have solved the problem using golang and MySQL.

_, table_check := db.Query("select * from " + table + ";")

    if table_check == nil {
        fmt.Println("table is there")
    } else {
        fmt.Println("table not there")
    }

I have used db.Query() which returns values and and error, here I checked only error.

I think most people thought I want to do it in MySQL way, I just wanted to learn how to use golang to do MySQL operations.

Upvotes: 4

Related Questions