I'm really struggling to get this SQL into my head while using java.
My problem is: I want to use a variable in my sql Query, and i cant seem to get it working, it catches the correct value(i'm showing it on a label), But it doesnt show any records, yet, if i replace the variable for a '5', it shows me the correct record...
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = MySqlConnect.ConnectDb();
int idaca = Integer.parseInt(idhist.getText());
String query1 = "SELECT t.nome, h.Valor_Atual, h.Valor_Antigo, a.nome
FROM Tecnologias t, Historico h, Academista a
WHERE h.Id_Academista = a.Id_Academista AND a.Id_Academista = "+idaca+" AND h.Id_Tecnologia = t.Id_Tecnologia
AND (h.Valor_Atual || h.Valor_Antigo || t.nome) LIKE '%" + ValToSearch + "%'";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query1);
historico history;
while (rs.next()) {
history = new historico(rs.getString("Nome"), rs.getInt("Valor_Antigo"),
rs.getInt("Valor_Atual"), rs.getString("Nome"));
historicoList.add(history);
} //END WHILE
} //END TRY
catch (Exception e) {
JOptionPane.showInputDialog(null, e);
}//END CATCH
Thats my code so far... The ValToSearch is working fine, tho...
Thank you in advance! Cheers
Put an space before AND h.Id_Tecnologia. That should solve your problem.
You are not afraid that in ValToSearch you get something like ' OR 1 IN (DELETE * FROM Tecnologias )?
Use parametr escaping or better some query builder
Related
The user must choose a Resort ID from the table that is displayed and the make a booking. I can't seem to find my problem, I want to print the name of the Resort that they are making a booking at.
String x = jTextFieldID.getText();
Integer Resort = Integer.valueOf(x);
int resort = Integer.parseInt(x);
String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = "+Resort;
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, resort);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
String resortName = rs.getString("RESORT_NAME");
JOptionPane.showMessageDialog(null,
"You want to book at " + resortName);
}
You have to use rs.next() :
ResultSet rs = pstmt.executeQuery(sql);
String resortName = "";
if(rs.next()){//<<-----------------------------
resortName = rs.getString("RESORT_NAME");
}
JOptionPane.showMessageDialog(null, "You want to book at "+resortName);
If you want to get many results you can use while(rs.next){...} instead.
Note? for a good practice, don't use upper letter in beginning for the name of your variables ResortName use this instead resortName
You need to test over the ResultSet result before trying to read from it:
if(rs.next()) {
String ResortName = rs.getString(1);
JOptionPane.showMessageDialog(null, "You want to book at "+ResortName);
}
And you can use getString(1) to get the RESORT_NAME, check ResultSet .getString(int index) method for further details.
The error is that sql is passed to Statement.executeQuery(String) too, instead of the PreparedStatement.executeQuery().
int resort = Integer.parseInt(x);
//String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = ?";
String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = " + resort;
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
//pstmt.setInt(1, resort);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
String resortName = rs.getString("RESORT_NAME");
JOptionPane.showMessageDialog(null,
"You want to book at " + resortName);
}
}
} catch (SQLException ex) {
Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex);
}
Commented is the alternative usage of a prepared statement (as normally used).
Also you should close statement and result set, which can be done automatically with try-with-resources as above.
Oh, oversaw almost, that rs.next() must be called. (The others already mentioned.)
I've encountered an error and I'm not able to figure out my mistake. I've done my research and haven't found an appropriate answer for my question.
This is my code:
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String CN, CNo, MN, NT, SNo, VIP, T, D;
CN = TF1.getText();
CNo = TF2.getText();
MN = TF3.getText();
NT = TF4.getText();
SNo = TF5.getText();
VIP = TF6.getText();
T = TF7.getText();
D = TF8.getText();
try
{
Class.forName("java.sql.DriverManager");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/devika", "root", "rockgirl12");
Statement stmt = (Statement) con.createStatement();
String query = "INSERT INTO Maintenance VALUES ('"+CN+"',"+CNo+",'"+MN+"',"+NT+",'"+SNo+"','"+VIP+"','"+T+"','"+D+"');";
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(this, "Record added succesfully!");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
What I'm trying to do here is I'm adding data to my SQL database through a form I designed in Java Netbeans. I've attached the form I've created here.
My Form
Help would be greatly appreciated :)
Exactly what the error says. The number of columns and the fields in valules do not match. This sort of insert without specifing the column names isn't the best practice by any stretch. You should do
String query = "INSERT INTO Maintenance(col1, col2, col3, col4,..) VALUES ('"+CN+"',"+CNo+",'"+MN+"',"+NT+",'"+SNo+"','"+VIP+"','"+T+"','"+D+"');";
In fact, you shouldn't be doing this sort of string concatenation either. It's far better to use prepared statements. The current approach does not ensure that the data is properly escaped before being saved.
I try to execute INSERT query in cycle:
String selectTableSQL = "SELECT * "
+ "FROM testTable";
ResultSet rs = stmt.executeQuery(selectTableSQL);
while (rs.next()) {
String rangeName = rs.getString("RANGENAME");
insertTableSQL = "INSERT INTO testTable2 "
+ "VALUES ('" + rangeName + "')";
try {
stmt.executeUpdate(insertTableSQL);
} catch (SQLException e) {
// do nothing
}
But after one iteration this cycle breaks. If I don't execute INSERT query and print rangeName to screen everything works perfectly (there are a lot of values, not only one). So the problem is in statement execution. How can I solve it?
Thank you very much!
Of course it does: you're using the same stmt
Create a new stmt2 variable and use it inside loop without destroying the previous one.
First: Never do so
} catch (SQLException e) {
// do nothing
}
Add a e.printStackTrace() to the catch block.
I think you get an exception when you do so. You may need a second statement variable.
I am writing a query to load my data in a jlist
public void showtitle(){
DefaultListModel model = new DefaultListModel();
booklist.setModel(model);
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection conn = DriverManager.getConnection("jdbc:derby://"+X, "APP", "app");
Statement stmt = conn.createStatement();
String query="SELECT TITLE FROM BOOK WHERE ISBN LIKE '%"
+ code.getText().toUpperCase()+"%' OR "
+ " TITLE LIKE '%"+name.getText().toUpperCase()+"%' ";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String isbn = rs.getString(1);
model.addElement(isbn);
}
}
catch ( ClassNotFoundException | SQLException ex) {
JOptionPane.showMessageDialog(null, "Unknown Error!! Data cannot be displayed!" + ex);
}
}
I am calling this method like this :
private void codeKeyReleased(java.awt.event.KeyEvent evt)
{
showtitle();
}
After inserting 1000 data my query is running very slow. Is my procedure not good? Is there some fatal mistake? What should I do?
You're doing more than just executing a query in your method.
You're also creating the JDBC connection, which is probably a much more expensive operation.
Trying creating the JDBC connection once and saving it somewhere in your application.
Then when the user runs your key-released event, just run your query and fetch the results.
It looks like your case doesn't really need the power of 'LIKE', maybe just use '=' instead? 'LIKE' is much mor powerful but may not be able to utilize indices, so you may end up performing a full table scan (see Use '=' or LIKE to compare strings in SQL? )
When I used the follow snippets to update Oracle Clob:
String toBeUpdated = ""
StringReader reader = new StringReader(toBeUpdated);
pStmt.setCharacterStream(parameterIndex,reader , toBeUpdated.length());
When the length of string "toBeUpdated" is a little bit bigger(general more than 5000) and a value had been ready stored into db, it was without any exceptions and the expected value was returned in method executeUpdate() when I ran the above codes. but the stranger probelm is that I checked DB and found the column was null.(it should be updated with new value).
it did not happened every time but a little bit randomly.
I tried use pStmt.setString() instead of pStmt.setCharacterStream everything was going to be fine. as far as I know setString is limited of maximize string size(63000) it cannot be proposed solution.
Is anybody can light me or experienced this?
Oracle provide Classes for store CLOB from strings. I have use the following code and it works fine:
long id = ...
String content = ... // CLOB content
try {
Class.forName ("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#MY_SERVER:1521:MY_DB", "user", "pass");
String query = "UPDATE MY_TABLE SET MY_CLOB_COLUMN = ? WHERE ID = ? ";
OraclePreparedStatement opstmt = (OraclePreparedStatement)conn.prepareStatement(query);
opstmt.setStringForClob(1, content);
opstmt.setLong(2, id);
int result = opstmt.executeUpdate();
System.out.println("Resultado para : " + tabla + " - " + columna + " - " + id + ":" + result);
} catch (SQLException ex) {
//Log here
} catch (ClassNotFoundException ex) {
//Log here
}