Ms access autoNumber when retrieving data - netbeans-7

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");
}

Related

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();

using clearParameter() even thought PreparedStatement is being closed

private PreparedStatement InsertPS = null;
public boolean InsertInDB(String username, String password, double balance, String secret) {
boolean ans = false;
try {
InsertPS = con.prepareStatement("Insert into BankDB values(?,?,?,?)");
String data[] = AMC.SendtoDB(password, secret);
InsertPS.setString(1, data[0]);
InsertPS.setString(2, username);
InsertPS.setString(3, data[1]);
InsertPS.setDouble(4, balance);
int rows = InsertPS.executeUpdate();
if (rows != 0) {
ans = true;
}
InsertPS.clearParameters();
} catch (SQLException sqlInite) {
System.out.println("SQL Error in InsertInDB method: " + sqlInite);
} finally {
try {
InsertPS.close();
} catch (SQLException sqle) {
System.out.println("SQL Exception in InsertInDB method finally clause : " + sqle);
}
}
return ans;
}
Above is the InsertInDB() method given,
It has a InsertPS PreparedStatement Object.
Here is it necessary to use clearParameters() method even though i am closing the InsertPS object at the end of the method.
(I have provided a separate method to close the connection object)
also another question: Is it a good idea to create PreparedStatement Object's outside any method within a class,initializing using Constructor and Say for example Once all Object's (each in different method) are used, close all PreparedStatement Objects using a separate method.
public class JavatoDB {
Driver DM = null;
Connection con = null;
PreparedStatement InsertPS = null;
PreparedStatement BalancePS = null;
PreparedStatement DeletePS = null;
PreparedStatement UpdatePS = null;
PreparedStatement SearchDB = null;
ResultSet RS = null;
ResultSetMetaData RSMD = null;
AdminControl AMC = null;
public JavatoDB() {
AMC = new AdminControl();
try {
DM = new com.mysql.jdbc.Driver();
con = DriverManager.getConnection("jdbc:mysql://localhost/javadb", "java", "javaaccess");
InsertPS = con.prepareStatement("Insert into BankDB values(?,?,?,?)");
BalancePS = con.prepareStatement("Select BALANCE from BankDB where ACCNAME=? AND ACCPIN = ?");
DeletePS = con.prepareStatement("Delete from BankDB where ACCNAME = ? AND ACCPIN = ? ");
UpdatePS = con.prepareStatement("Update BankDB set BALANCE = (BALANCE + ?) where ACCNAME = ? AND ACCPIN = ?");
SearchDB = con.prepareStatement("Select ID AND ACCPIN from BankDB where ACCNAME = ? ");
} catch (SQLException JavatoDBContrsuctor) {
System.out.println("SQL Error in JavatoDBConstructor: " + JavatoDBContrsuctor);
}
}
public boolean InsertInDB(String username, String password, double balance, String secret) {
boolean ans = false;
try {
String data[] = AMC.SendtoDB(password, secret);
InsertPS.setString(1, data[0]);
InsertPS.setString(2, username);
InsertPS.setString(3, data[1]);
InsertPS.setDouble(4, balance);
int rows = InsertPS.executeUpdate();
if (rows != 0) {
ans = true;
}
InsertPS.clearParameters();
} catch (SQLException sqlInite) {
System.out.println("SQL Error in InsertInDB method: " + sqlInite);
}
return ans;
}
Suggestion's or Criticism on other aspects of code are also welcome.
For the first question, when you call:
con.prepareStatement()
a new preparedStatement is created, then parameters dont survive, i mean you dont need to clear then.
About the second question, in your implementation i cant see where you close your preparedStatement, and if you only add close, next time method will fail. Then, it is usual to create the preparedStatement and close it in the same method.

How to auto Increment a primarykey in JDBC sql

can you please guys help me, i'm having trouble on making my primary key into auto-increment, My table name is books and the column that i want to be auto-increment is serial_no which is a primary key.
public class donate extends javax.swing.JFrame {
Connection con;
Statement stmt;
ResultSet rs;
PreparedStatement pst;
DefaultTableModel loginModel = new DefaultTableModel();
int curRow = 0;
/**
* Creates new form donate
*/
public donate() {
initComponents();
DoConnect();
showAll();
}
void showAll(){
try{
rs = stmt.executeQuery("SELECT * FROM books");
while(rs.next())
{
String book = rs.getString("book_title");
String categorie = rs.getString("category");
String status = rs.getString("book_status");
String donators = rs.getString("donator");
int serial_nos = rs.getInt("serial_no");
loginModel.addRow(new Object[]{book, categorie, status, donators, serial_nos});
}
}catch(SQLException err){
System.out.println(err);
}
}
void DoConnect( ) {
try{
//CONNECT TO THE DATABASE
String host = "jdbc:derby://localhost:1527/Dafuq7";
String uName ="Dafuq7";
String uPass ="Dafuq7";
con = DriverManager.getConnection(host, uName, uPass);
//EXECUTE SOME SQL AND LOAD THE RECORDS INTO THE RESULTSET
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM books";
rs = stmt.executeQuery(sql);
}
catch(SQLException err){
JOptionPane.showMessageDialog(donate.this, err.getMessage());
}
}
and here is for may button, which when i input all the data will be submitted to my table books
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String bookttl = bookt.getText();
String yourn = yn.getText();
String categ = cat.getSelectedItem().toString();
String bstat = bs.getSelectedItem().toString();
try {
rs.moveToInsertRow();
rs.updateString( "book_title", bookttl );
rs.updateString( "category", yourn );
rs.updateString( "book_status", categ );
rs.updateString( "donator", bstat );
loginModel.addRow(new Object[]{bookttl, yourn, categ, bstat});
rs.insertRow( );
stmt.close();
rs.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM books";
rs = stmt.executeQuery(sql);
}
catch (SQLException err) {
System.out.println(err.getMessage() );
}// TODO add your handling code here:
}
BTW i found another way around by doing this, grabbing my table and reconstructing it and put this code in the create table script
SERIAL_NO INTEGER default AUTOINCREMENT: start 1 increment 1 not null primary key
Simply define your serial_no column as int primary key generated always as identity and then Derby will automatically assign the numbers for you. Here is some example code:
public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection(
"jdbc:derby:C:/__tmp/derbytest;create=true")) {
String sql;
sql = "DROP TABLE books";
try (Statement s = conn.createStatement()) {
s.executeUpdate(sql);
} catch (Exception e) {
// assume table did not previously exist
}
sql = "CREATE TABLE books (" +
"serial_no int primary key " +
"generated always as identity, " +
"title varchar(100))";
try (Statement s = conn.createStatement()) {
s.executeUpdate(sql);
}
sql = "INSERT INTO books (title) VALUES (?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, "The Book of Foo");
ps.executeUpdate();
ps.setString(1, "The Book of Bar");
ps.executeUpdate();
ps.setString(1, "The Book of Baz");
ps.executeUpdate();
}
sql = "SELECT * FROM books";
try (Statement s = conn.createStatement()) {
try (ResultSet rs = s.executeQuery(sql)) {
while (rs.next()) {
System.out.println(String.format(
"%d: %s",
rs.getInt("serial_no"),
rs.getString("title")));
}
}
}
} catch (SQLException se) {
se.printStackTrace(System.out);
System.exit(0);
}
}
which produces
1: The Book of Foo
2: The Book of Bar
3: The Book of Baz

netbeans sql's statment using Like operator

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());
}

Can anyone see why this SQL insert will not work? (Exception to String and Date to String Inserted) - JDBC

Im trying to basically make a log of errors generated from a Java program and save them in an SQL table with 2 colums( Error and Date )
Try and catch sends the error to the method which should hopefully insert into database but its failing somewhere. Im new enough to Java so im not sure how to debug it properly or get more details on wahts going wrong and where
Heres the method.
public void createErrorLog(Exception error) throws SQLException{
// Error as String
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
error.printStackTrace(pw);
sw.toString(); // stack trace as a string
String errorOne = sw.toString();
System.out.println(errorOne);
// Date
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
String dateString = dateFormat.format(date);
Connection conn = null;
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected to database.");
String insertSaleProperty = "INSERT INTO ErrorLogs"
+ "(Error, "
+ "Time, "
+ "(?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(insertSaleProperty);
preparedStatement.setString(1, errorOne);
preparedStatement.setString(2, dateString);
// execute insert SQL statement
preparedStatement.executeUpdate();
} catch (SQLException e) {
System.err.println("Cannot write to database.");
} finally {
if(conn != null){
conn.close();
}
}
}
Try the following.
String insertSaleProperty = "INSERT INTO ErrorLogs"
+ "(Error,Time) values "
+ "(?,?)";
String insertSaleProperty = "INSERT INTO ErrorLogs"
+ "(Error, "
+ "Time, "
+ "(?,?)";
Should probably be:
String insertSaleProperty = "INSERT INTO ErrorLogs "
+ "(Error, Time) "
+ "VALUES (?,?)";