O
O
Orkhan Hasanli2018-09-17 14:46:50
Java
Orkhan Hasanli, 2018-09-17 14:46:50

What is the best way to store code snippets in a database?

Good afternoon!
I am writing a small java + javafx + sqlite program that will store code snippets in a database.
I encountered the following gap - the written code, when trying to add it to the database, gives an error, although if you enter just text instead of the code, then everything works.
I suspect that the problem is rather with the sanitization of symbols ... Hence the question - how best to store snippets in the database? Should the snippet be base64 encoded and rendered decoded, or do characters need to be sanitized?
Error code:

[SQLITE_ERROR] SQL error or missing database (near "publish": syntax error)

@Override
    public void ButtonAdd(ActionEvent actionEvent) {

        snippet.setSnippetTitle(txtTitle.getText());
        snippet.setSnippetCode(txtCode.getText());
        snippet.setSnippetDescription(txtDescr.getText());

        // Добавляем данные в БД
        try {
            SQLiteConfig config = new SQLiteConfig();
            c = db.getInstance().getConnection();

            PreparedStatement stat = c.prepareStatement("INSERT INTO snippets (snippetTitle, snippetCode, snippetDescr) VALUES ('" + snippet.getSnippetTitle() +
                    "','" + snippet.getSnippetCode() + "','" + snippet.getSnippetDescription() +
                     "')");
            stat.executeUpdate();

        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        ButtonCancel(actionEvent);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Cheremisin, 2018-09-17
@azerphoenix

You don't know how to cook it right. We bet it will work.

// ....
PreparedStatement stat = c.prepareStatement("INSERT INTO snippets (snippetTitle, snippetCode, snippetDescr) VALUES (?,?,?)");
stat.setString(1,snippet.getSnippetTitle());
stat.setString(2,snippet.getSnippetCode());
stat.setString(3, snippet.getSnippetDescription());
stat.executeUpdate();
// ....

PS. The answer is here - https://docs.oracle.com/javase/7/docs/api/java/sql...
and here - https://docs.oracle.com/javase/tutorial/jdbc/basic...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question