<p>I need to input values explicitly into an Insert statement for MySQL to test some code, but I do not know what to put for variables of type sql.NullInt64. If anyone knows it would help a lot. Thanks!</p>
<hr/>**评论:**<br/><br/>Kraigius: <pre><p>Does it not work when you insert the NullInt64 variable?
Your column type would be BIGINT.</p>
<p>You just create a new NullInt64 in go and set the Int64 field to your value and set valid to true.</p></pre>fnetma: <pre><p>Could you show me what you mean? Sorry first time using MySQL and Go. Thanks for the help!</p></pre>Kraigius: <pre><p>Sure, look at this:</p>
<p><a href="https://stackoverflow.com/questions/40266633/golang-insert-null-into-sql-instead-of-empty-string" rel="nofollow">https://stackoverflow.com/questions/40266633/golang-insert-null-into-sql-instead-of-empty-string</a></p>
<p>Go doesn't really have the concept of nullable unlike say, C# (<code>int? value = null;</code>)</p>
<p>However, in the <code>database/sql</code> package we have a few types to help around.
<a href="https://golang.org/pkg/database/sql/#NullInt64" rel="nofollow">https://golang.org/pkg/database/sql/#NullInt64</a></p>
<p>They are just wrappers to help around. They contain the variable of the type that you want and a bool to tell whether or not it's a null.</p>
<p>When you read from the database from a nullable BIGINT column that have "42" as the value it will decode into a NullInt64 in Go.</p>
<p>The Int64 field will be set to 42 and Valid will be true.</p>
<p>If the same column is a null value, Int64 will be 0 (default of the int64 type) with Valid to false.</p>
<p>So to know if you got a null, check the Valid field first. If you want to write a null, just set the Valid field to false.</p></pre>fnetma: <pre><p>Ok I think I have it correct but I am now getting an error that says " Composite literal uses unkeyed fields" do you have idea what it means ?</p></pre>PaluMacil: <pre><blockquote>
<p>Composite literal uses unkeyed field</p>
</blockquote>
<p>I hadn't seen that error myself, but <a href="https://stackoverflow.com/questions/36273920/disable-go-vet-checks-for-composite-literal-uses-unkeyed-fields" rel="nofollow">the first Google result</a> points out that if you use <code>go vet</code>, you get a lint warning for structs you declare a literal with the values and no field names. It isn't an error, so you can disable the rule in go vet, not use go vet, or probably ignore it. According to some, you should instead specify the fields when you make a struct literal. Personally, I don't care much if there are only two fields in the struct.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传