Data too long for column error - String to Varchar issue

Hi,

I tried to find an answer on the web couldn’t find anything so asking here.

The line stmt.Exec(u.Name) causes Error 1406: Data too long for column 'name' at row 1. The name field in MySQL DB is set to Varchar 11. If I change it to text in DB it does work but that’s a hack. Any way of solving this issue.

Thanks

type User struct {
	ID uint16
	Name string
}
func Insert(u *User) (int64, error) {
	stmt, err := r.db.Prepare("INSERT INTO users (name) VALUES (?)")
	if err != nil {
		return 0, err
	}

	res, err := stmt.Exec(u.Name) // u.Name is set to 'Hello World' so it is short!
	if err != nil {
		return 0, err
	}

	id, err := res.LastInsertId()
	if err != nil {
		return 0, err
	}

	// By the way, should I call `defer` or `close` on anything?

	return id, nil
}

Does it work if you make the length 12? I’m not familiar with MySQL, but does the Varchar 11 include a null-terminator?

I pretend like I didn’t ask this question. Disastrously Awkward! Obviously the field is set to 11 which is short and should have been e.g. 255 instead.

Moving on from the disaster, should I call defer or close on anything at the end?

Note: I am a learner so sorry for doggy questions.

You can close your statement

`defer stmt.Close()`

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.