How to process the string for storing in MySQL db?

polaris · · 722 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi,</p> <p>In this moment I writing a little application for web at Golang. I wish to save a string from HTML form to MySQL database but I have worry about special characters and escape sequences. I wrote a little function with regex but I think that it is not enough for a production (&#34;really world&#34; ;) ). Maybe you know something about frameworks or library for Golang for safety string processing? (like as mysql_real_escape_string in PHP)</p> <p>Thank you ;)</p> <hr/>**评论:**<br/><br/>brokedown: <pre><p>Those escapes are really only needed if you&#39;re creating a query string by hand with data, which you should never do with dynamic arguments.</p> <p>In Go, you would do something like:</p> <pre><code>_,err:=db.Exec(&#34;insert into foo (fieldA, fieldB) values (?, ?)&#34;, valueA, valueB) </code></pre></pre>Brasilikum: <pre><p>Citing a <a href="http://stackoverflow.com/questions/26345318/how-can-i-prevent-sql-injection-attacks-in-go-while-using-database-sql">stack overflow answer</a>:</p> <p>As long as you&#39;re using Prepare or Query, you&#39;re safe.</p> <p>// this is safe db.Query(&#34;SELECT name FROM users WHERE age=?&#34;, req.FormValue(&#34;age&#34;)) // this allows sql injection. db.Query(&#34;SELECT name FROM users WHERE age=&#34; + req.FormValue(&#34;age&#34;))</p></pre>whitedruid: <pre><p>Thanks! I try to use both solutions and I have no feel a diffrent but I&#39;m newbie at software development at Go ;) ..... I found this: <a href="https://astaxie.gitbooks.io/build-web-application-with-golang/content/en/09.4.html" rel="nofollow">https://astaxie.gitbooks.io/build-web-application-with-golang/content/en/09.4.html</a></p></pre>Brasilikum: <pre><p>In the first case you are concatenating everything to one string and then pass it to the db-package. If it contains illegal characters, they are evaluated. If you pass many strings, the dB package may check every single one for illegal characters</p></pre>3264128256: <pre><p>As others have said if you&#39;re worried about SQL injection, prepared statements will get rid of those.</p> <p>If you&#39;re worried about displaying the said HTML on a browser, it&#39;s a different issue. Go&#39;s <a href="https://golang.org/pkg/html/template" rel="nofollow">template/html</a>outputs HTML which is safe against code injection. Or if you&#39;re using something else you could process it through <a href="https://golang.org/pkg/html/template/#HTMLEscapeString" rel="nofollow">HTMLEscapeString</a> or <a href="https://golang.org/pkg/html/template/#HTMLEscape" rel="nofollow">HTMLEscape</a></p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

722 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传