netbeans sql's statment using Like operator - netbeans-7

I am trying to pass value from Jcombobox and I used Like Operator in order to retrieve data from Database ..
I need to retrieve all data related to a chosen month from combobox
String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE '?%'";
try {
ps = con.prepareStatement(sql);
ps.setString(1, cmb.getSelectedItem().toString());
rs = ps.executeQuery();
table_PatuentReg.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}

String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE '"+cmb.getText().toString()+"%'";
Use this format.
this will help more...

You need to change the query and add the % in the prepared statement value where we are setting the value for string.
String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE ?";
try {
ps = con.prepareStatement(sql);
ps.setString(1, cmb.getSelectedItem().toString()+"?");
rs = ps.executeQuery();
table_PatuentReg.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}

Try putting it directly in the ? mark sign, like so
String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE '"+cmb.getSelectedItem().toString()+"%'";
try {
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
table_PatuentReg.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}

Related

Whats wrong with this SQL Command? It should work

Whats wrong with this sql code? Syntax should be ok or not?
public void setArtikelIdRegalfach(ArrayList <Integer> arikel_ID, int Regal_ID) { // Setzt die Regalfach ArtikelID
try {
String query = "UPDATE WARENLISTE SET ARTIKEL_ID Values (" + arikel_ID + ") WHERE Regal_ID = " + Regal_ID;
st.executeUpdate(query);
}
catch(Exception e) {
System.out.println(e);
}
}
Update statements in SQL do not take a VALUES clause. On top of this, you should be using a prepared statement. Here is a corrected version:
String sql = "UPDATE WARENLISTE SET ARTIKEL_ID = ? WHERE Regal_ID = ?";
try (Connection conn = DriverManager.getConnection("...");
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, arikel_ID);
ps.setInt(2, Regal_ID);
ps.executeUpdate();
}
catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}

Unable to set data to textField from tableView - on Mouseclick and Up and Down Arrow keys (H2 Database)

I am a recent user of the h2 database, I need some assistance with the SQL syntax.
I'm able to retrieve data from the h2 dB and set it into JavaFX tableView, On performing the mouseclick or buttonpress action (Up & Down arrows) the intended behaviour is to display the current row of data from the tableView into the textfields, below is the code.
I'm getting the following exception:
Invalid value "1" for parameter "parameterIndex" [90008-193]
I'm certain this exception is due to SQL grammar unique to the H2 database, as the placeholder (' "+slnoField.getText()+" ' ") works fine in other databases. Please could you suggest the correct syntax or a solution. Many thanks.
#FXML
public void UpdateTable(){
data.clear();
try
{
conn = lrconn.getDatabaseConnection();
String sql = "SELECT * from APP_TABLE ;
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next())
{
data.add(new TestPOJO(
rs.getString("SLNO"),
rs.getString("NAME")
));
Table.setItems(data);
}
pst.close();
rs.close();
}
catch(Exception e1)
{
e1.printStackTrace();
}
Table.setOnMouseClicked((MouseEvent me) ->{
try{
conn = lrconn.getDatabaseConnection();
TestPOJO user = (TestPOJO)Table.getSelectionModel().getSelectedItem();
String sql = "SELECT * from APP_TABLE where SLNO =' "+slnoField.getText()+" ' ";
pst = conn.prepareStatement(sql);
pst.setString(1, user.getSLNO());
rs = pst.executeQuery();
while(rs.next()){
slnoField.setText(rs.getString("SLNO"));
nameField.setText(rs.getString("NAME"));
}
rs.close();
pst.close();
}catch(SQLException ex){
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
);
Table.setOnKeyReleased((KeyEvent e) ->{
if(e.getCode() == KeyCode.UP || e.getCode() == KeyCode.DOWN){
try{
TestPOJO user = (TestPOJO)Table.getSelectionModel().getSelectedItem();
String sql = "SELECT * from APP_TABLE where SLNO =' "+slnoField.getText()+" ' ";
pst = conn.prepareStatement(sql);
pst.setString(1, user.getSLNO());
rs = pst.executeQuery();
while(rs.next()){
slnoField.setText(rs.getString("SLNO"));
nameField.setText(rs.getString("NAME"));
catch(IOException | SQLException ex){
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
);
}
You're not using the PreparedStatement correctly. Place ? at locations where you want to insert parameters in the query string. You don't seem to add one of those:
String sql = "SELECT * from APP_TABLE where SLNO = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, user.getSLNO());
rs = pst.executeQuery();

PreparedStatement SetString doesn't work (case Oracle)

I don't have an idea why this method gets an error
public TdPegawai getTdPegawai(String nip) throws Exception {
PreparedStatement ps = null;
try {
TdPegawai tp = new TdPegawai();
sql = "select * "
"from TD_PEGAWAI " +
"where NIP=? ";
ps = connection.prepareStatement(sql);
ps.setString(1, nip);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// tp.setblablabla();
}
rs.close();
return tp;
} finally {
ConnectionUtil.closePreparedStatement(ps);
}
}
My SQL variable just returns SELECT * FROM TD_PEGAWAI WHERE NIP=?
My nip variable can return a value.
Is there any something wrong with my preparestatement or setstring ?

Oracle columns update not happpening

I am trying to update a few columns in a Oracle table from my C# code.
Here is my method:
private static bool UpdateOracleTable(OracleTable table, string whereClause, List<int> entIDs)
{
try
{
var tableName = table.ToString();
using (OracleConnection conn = new OracleConnection(_oracleConnection))
{
conn.Open();
foreach (var id in entIDs)
{
whereClause = String.Format(whereClause, id);
var query = Resources.UpdateOracle;
query = String.Format(query, tableName, "20", DateTime.Now.ToString("yyyy/MM/dd"), whereClause);
using (OracleCommand cmd = new OracleCommand(query, conn))
{
cmd.ExecuteNonQuery();
}
}
}
return true;
}
catch (Exception ex)
{
Log.Debug(LogType.Error, ex);
return false;
}
}
Here is the Query:
UPDATE
{0}
SET
SYNC_STATUS = '{1}'
,SYNC_DATE = TO_DATE('{2}', 'yyyy/mm/dd')
{3}
And the where clause will look something like:
WHERE ID = {0}
This method updates about 10 records, and the rest stays null. This mehod does return true, and I have debugged, no exception is thrown.
Why does it not update all records?
This isn't an answer but might help debug the problem.
Instead of the like:
cmd.ExecuteNonQuery();
put in this:
int count = cmd.ExecuteNonQuery();
if (count == 0)
{
Console.WriteLine("");
}
Put a break on the Console.WriteLine("") and run it. The debugger will stop if no rows were updated. You can then check the query, and whether or not that ID actually exists.
The problem was with the WHERE clause. Since it contains a place holder {0}, after I I formatted the WHERE clause, the ID always stayed to the value it was formatted with first.
This is what my new method looks like.
private static bool UpdateOracleTable(OracleTable table, string whereClause, List<int> entIDs)
{
try
{
var tableName = table.ToString();
using (OracleConnection conn = new OracleConnection(_oracleConnection))
{
conn.Open();
foreach (var id in entIDs)
{
string originalWhere = whereClause;
originalWhere = String.Format(originalWhere, id);
var query = Resources.UpdateOracle;
query = String.Format(query, tableName, "20", DateTime.Now.ToString("yyyy/MM/dd"), originalWhere);
using (OracleCommand cmd = new OracleCommand(query, conn))
{
bool success = cmd.ExecuteNonQuery() > 0;
}
}
}
return true;
}
catch (Exception ex)
{
Log.Debug(LogType.Error, ex);
return false;
}
}
As can be seen, I added a variable 'originalWhere', that gets formatted, but most importantly, is being set to original WHERE clause parameter passed, so that it will always contain the place holder.

Ms access autoNumber when retrieving data

can anyone help with retrieving value from ms access db
the problem with auto number, I want to show it in Jtextfield when I click over a record into the table..
I asked before this question, but no one answer me.
Please help me with this problem as soon as posible.
try {
int row = table_BP.getSelectedRow();
String Table_Clicked = table_BP.getModel().getValueAt(row, 0).toString();
String sql = "Select * from Blood_pressure where Patient_Id='" + Table_Clicked + "'";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()) {
try {
String add1 = rs.getString("BP_Test_ID").toString();
txt_testNo.setText(add1);
String add2 = rs.getString("Patient_Id");
txt_PID.setText(add2);
String add3 = rs.getString("Date_Of_test");
DC_Date.setDateFormatString(add3);
String add4 = rs.getString("Blood_presure");
txt_BP.setText(add4);
String add5 = rs.getString("Remarks");
TA_Remarks.setText(add5);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "sdsdsd");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "nnnnnnnnnnnnnnnnnnnn");
}