dennohpeter
dennohpeter

Reputation: 441

How to escape String data in Sql

This is what I have

String LabelText= SemiLabel.getText(); //the value in the label is "Year 1 Sem I";
Connection conn=dbc.connect() ;

This is what I have

String LabelText= SemiLabel.getText(); //the value in the label is "Year 1 Sem I";
Connection conn=dbc.connect() ;
Resultset rs =conn.createStatement().excuteQuery("Select SchoolOfMusic, Semester FROM Units, registeredUnitsTable WHERE Semester = " +LabelText) 

The problem is am getting an syntax error near '1 Sem I' at line one.

How can I escape it in sql to get 'Year 1 Sem I' and not '1 Sem I', am comparing my data received with the one the database Column Semester.

Upvotes: 0

Views: 69

Answers (2)

fabian
fabian

Reputation: 82461

Use a PreparedStatement to insert the string to the query:

Connection conn=dbc.connect();
PreparedStatement ps = conn.prepareStatement("Select SchoolOfMusic, Semester FROM Units, registeredUnitsTable WHERE Semester = ?");
ps.setString(1, LabelText);
ResultSet rs = ps.executeQuery();

Upvotes: 3

Bohemian
Bohemian

Reputation: 424983

You need to specify your text as a single SQL literal value in the query. The simple way is to surround the text in single quotes:

Resultset rs =conn.createStatement()
  .excuteQuery("Select SchoolOfMusic, Semester FROM Units, registeredUnitsTable WHERE Semester = '"
     + LabelText + "'")

The better way is to let the driver handle it using a placeholder and calling setObject().

Upvotes: 0

Related Questions