Search code examples
databaseoledbexception

How to insert a hyperlink into a database?


Hi guys I am trying to put a social share button to my article dynamically. I want to insert a social share script along with my article text into a database and display it with a unique share link. so I am coding this way. This might not be a good idea but I would like to know if its possible this way.

string socialButton = "
<div id='social_nav_horizontal'>    <h3>        Bookmark or Share This Post</h3>    <ul>        <li>            <a class='delicious' href='http://del.icio.us/post?url=Your website title' title='Share this on del.icio.us'>Delicious</a></li>     <li>            <a class='facebook' href='http://www.facebook.com/sharer.php?u=http://yourwebsite.com'>Facebook</a></li>        <li>            <a class='stumbleupon' href='http://www.stumbleupon.com/submit? url=http://www.yoursite.com/'>Stumble</a></li>      <li>            <a class='twitter' href='http://twitter.com/home?status=Your Website Title- http://yourwebsite.com@TwitterUserName'>Twitter</a></li>    </ul></div><p>  &nbsp;</p>";

So "insert into myArticleTable (articleText) values ('"+socialButton + articleText.Text+"')"; But it throws an exception when trying to insert.

System.Data.OleDb.OleDbException: Syntax error (missing operator) in query expression ''

This work only if I directly past it to my ckeditor (wysiwyg) rich text editor and execute the insert statement on a button click event.

Can you help?

Thank you


Solution

  • Because a single quote is used for indicating the start and end of a string, you need to escape it. The short answer is to use two single quotes - '' - in order for a SQL database to store the value as '.

    Ex:-
    Insert into Person
    (First, Last)
    Values
    ('Joe', 'O''Brien')
    

    Look at using REPLACE to sanitize incoming values:

    You want to check for '''', and replace them if they exist in the string with '''''' in order to escape the lone single quote.