I am trying to insert Appointment of the Doctor while selecting name of the Doctor it will insert ID only in the table database and updating Doctor Availability to 0
here is my code
try{
String sql = "INSERT INTO Appointment_Table (Doc_ID, Department_ID, SchedDate, Patient_ID) VALUES\n" +
"( (SELECT ID from User_Table where First_Name = ?), (SELECT Department_ID from User_Table WHERE First_Name = ?), ?, (Select Patient_ID from Patient_Records where First_Name = ?));";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(1, (String) DoctorNames.getSelectedItem());
pst.setString(2, (String) DoctorNames.getSelectedItem());
String add1 = ((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText();
String add2 = DoctorTime.getText();
pst.setString(3, add1+"-/-"+add2+"-PM");
pst.setString(4, (String) DoctorPatient.getSelectedItem());
try{
String sql1 = "Update User_Table set Availability = 0 where First_Name LIKE ?";
pst = pst = conn.prepareStatement(sql1);
rs = pst.executeQuery();
pst.setString(1, (String) DoctorNames.getSelectedItem());
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
try to add LIMIT 0,1 after SELECT just like this:
INSERT INTO Appointment_Table (Doc_ID, Department_ID, SchedDate, Patient_ID) VALUES
( (SELECT ID from User_Table where First_Name = ? LIMIT 0,1 ), (SELECT Department_ID from User_Table WHERE First_Name = ? LIMIT 0,1 ), ?, (Select Patient_ID from Patient_Records where First_Name = ? LIMIT 0,1 ));
it is for MySql DBMS for SQL Server use Top 1 keyword
SELECT TOP 1 ID from User_Table where First_Name = ?
add 3 combo box to your form one for Doc_ID and one for Department_ID and another one for Patient_ID
make this class
class ComboItem
{
private String key;
private String value;
public ComboItem(String key, String value)
{
this.key = key;
this.value = value;
}
#Override
public String toString()
{
return key;
}
public String getKey()
{
return key;
}
public String getValue()
{
return value;
}
}
Add the ComboItem to your comboBox.
comboBox.addItem(new ComboItem("doctor name ", "Doc_ID"));
comboBox.addItem(new ComboItem("doctor 2 name ", "Doc_ID 2"));
comboBox.addItem(new ComboItem("doctor 3 name ", "Doc_ID 3"));
Whenever you get the selected item.
Object item = comboBox.getSelectedItem();
String value = ((ComboItem)item).getValue();
the edit your SQL
INSERT INTO Appointment_Table (Doc_ID, Department_ID, SchedDate, Patient_ID) VALUES (combo_Doc_ID_value,combo_Department_ID_value,?,combo_Patient_ID_value)
Related
EDIT: I fixed the insert off by one mistake so I deleted that part of the question but still have the Bad value for type long error.
EDIT: the create statement for the small company table
create table small_company
(
first_name varchar(20),
last_name varchar(30),
address text,
emp_id serial not null
)
;
Created from:
create table company
(
first_name varchar(20),
last_name varchar(30),
company_name text,
address text,
city varchar(30),
province text,
postal varchar(7),
phone1 text,
phone2 text,
email text,
web text
)
;
create index name_priority
on company (first_name)
;
I'm getting this error saying "Bad value for type long :"
// insert values into the "small_company" table
long insertEmp(String first_name, String last_name, String address) {
String sql = "insert into small_company values (?,?,?)";
long id = 0;
try {
Connection conn = connect();
PreparedStatement pstmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1,first_name);
pstmt.setString(2,last_name);
pstmt.setString(3,address);
int affectedRows = pstmt.executeUpdate(); // returns number of affected rows
if (affectedRows > 0) { // means a row was affected so get the ID
try {
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
id = rs.getLong(1); // if cursor finds row with id, return it
}
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
catch (SQLException e){
System.out.println(e.getMessage());
}
return id;
}
public static void main(String[] args) {
Queries q1 = new Queries();
//q1.getRowCount("company");
//q1.displayTable();
//q1.displayCompany(); // <- what I use to display table!
//q1.findEmployee(10);
q1.insertEmp("Laura","Lane","Daily St. Planet co. NE"); //<-what I use to insert!
}
All help is greatly appreciated!
The first column in small_company is first_name and you can't use getLong() on a varchar column. You have to use getLong("emp_id") instead.
Alternatively you can tell the JDBC driver to only return the emp_id:
PreparedStatement pstmt = conn.prepareStatement(sql,new String[]{"emp_id"});
Then getLong(1) should work as well as only one column is returned (at least with an up-to-date JDBC driver).
I am having an issue with updating the Blob, the issue is that the pst.executeUpdate with not execute, however, if I take out the everything that relates the the Blob/Tryinng to update the Blob everything else will update i.e. ID, Name, Address etc. Everything functions as it should, the issue is just with the Blob.
updateEmployee.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Connection connection = null;
PreparedStatement pst = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:employeeDatabase.sqlite");
connection.setAutoCommit(false);
int idVal = Integer.parseInt(idTextField.getText());
String nameVal= nameTextField.getText();
String genderVal = genderTextField.getText();
String dobVal = dobTextField.getText();
String addressVal = addressTextField.getText();
String postcodeVal = postcodeTextField.getText();
String ninVal = ninTextField.getText();
String jobVal = jobtitleTextField.getText();
String startDateVal = startdateTextField.getText();
String salaryVal = salaryTextField.getText();
String emailVal = emailTextField.getText();
//Icon photoBlob = photoLabel.getIcon();
InputStream img = new FileInputStream(s);
String sql = "UPDATE employees set ID= '"+ idVal+"', Name = '"+ nameVal +"', Gender ='"+ genderVal+"', DOB='"+ dobVal+"', Address ='"+ addressVal+"', Postcode ='"+ postcodeVal+"', NIN ='"+ ninVal+"', JobTitle='"+ jobVal+"', StartDate ='"+ startDateVal+"', Salary ='"+ salaryVal+"', Email='"+ emailVal+"', Images='"+ img+" WHERE ID= '"+ idVal+"'";
pst = connection.prepareStatement(sql);
pst.setInt(1,Integer.parseInt(idTextField.getText()));
pst.setString(2, nameTextField.getText());
pst.setString(3, genderTextField.getText());
pst.setString(4, dobTextField.getText());
pst.setString(5, addressTextField.getText());
pst.setString(6, postcodeTextField.getText());
pst.setString(7, ninTextField.getText());
pst.setString(9, startdateTextField.getText());
pst.setString(10, salaryTextField.getText());
pst.setString(11, emailTextField.getText());
pst.setBytes(12, readFile(s));
pst.executeUpdate();
System.out.println("Employee Updated");
JOptionPane.showMessageDialog(null, "Employee has successfully been updated");
connection.commit();
pst.close();
connection.close();
}
catch ( Exception e1 ) {
if(idTextField.getText().equals("")){
JOptionPane.showMessageDialog(null, "Please Ensure An Employee Has Been Selected");
}
}
}});
Edit -
I can however, insert and delete blob files as well as retrieve. Just this updating is giving me an issue.
Your SQL command text is not valid for a parameterized query. Instead of creating a dynamic SQL command string with imbedded values ...
String sql = "UPDATE employees set ID= '"+ idVal+"', Name = '"+ nameVal +"', Gender ='"+ genderVal+"', DOB='"+ dobVal+"', Address ='"+ addressVal+"', Postcode ='"+ postcodeVal+"', NIN ='"+ ninVal+"', JobTitle='"+ jobVal+"', StartDate ='"+ startDateVal+"', Salary ='"+ salaryVal+"', Email='"+ emailVal+"', Images='"+ img+" WHERE ID= '"+ idVal+"'";
... you should be using a command string with question marks as parameter placeholders ...
String sql = "UPDATE employees set ID = ?, Name = ?, Gender = ?, DOB = ?, Address = ?, Postcode = ?, NIN = ?, JobTitle = ?, StartDate = ?, Salary = ?, Email = ?, Images = ? WHERE ID = ?;
... and then using .setInt, .setString, .setBytes et al to set the parameter values.
(Note also that it is actually redundant to SET the "ID" value when you are using ... WHERE ID = ?.)
I want to implement search filter for this table:
CREATE TABLE ACCOUNT(
ID INTEGER NOT NULL,
USER_NAME TEXT,
PASSWD TEXT,
FIRST_NAME TEXT,
LAST_NAME TEXT,
LAST_LOGIN DATE,
DATE_REGISTERED DATE,
ROLE INTEGER,
CAN_LOGIN INTEGER
)
;
-- ADD KEYS FOR TABLE ACCOUNT
ALTER TABLE ACCOUNT ADD CONSTRAINT KEY1 PRIMARY KEY (ID)
;
SELECT * FROM ACCOUNT
WHERE '" + searchString + "' IN (ID, USER_NAME, FIRST_NAME, LAST_NAME)
ORDER BY %S %S offset ? limit ?;
But when I have empty search filter I get this error:
org.postgresql.util.PSQLException: ERROR: invalid input syntax for integer: "null" Position: 30
How can I edit the SQL query in a way that WHERE clause will be skipped if searchString is empty?
Here is the Java method:
public List<AccountsObj> list(int firstRow, int rowCount, String sortField, boolean sortAscending) throws SQLException
{
String SqlStatement = null;
if (ds == null)
{
throw new SQLException();
}
Connection conn = ds.getConnection();
if (conn == null)
{
throw new SQLException();
}
String sortDirection = sortAscending ? "ASC" : "DESC";
SqlStatement = "SELECT * FROM ACCOUNT "
+ " WHERE '" + searchString + "' IN (ID, USER_NAME, FIRST_NAME, LAST_NAME)"
+ " ORDER BY %S %S offset ? limit ? ";
String sql = String.format(SqlStatement, sortField, sortDirection);
PreparedStatement ps = null;
ResultSet resultSet = null;
List<AccountsObj> resultList = new ArrayList<>();
try
{
conn.setAutoCommit(false);
boolean committed = false;
ps = conn.prepareStatement(sql);
ps.setInt(1, firstRow);
ps.setInt(2, rowCount);
resultSet = ps.executeQuery();
resultList = ProcessorArrayList(resultSet);
conn.commit();
committed = true;
}
finally
{
ps.close();
conn.close();
}
return resultList;
}
Using SQL to check for a null search string you can do:
SELECT * FROM account WHERE ? IS NULL OR ? IN (user_name, first_name, last_name)
Here the ? IS NULL will short-circuit if the parameter is NULL and the second part will not be evaluated.
Note that, I've used two parameter bindings with the same value (your search string) here and that the ID column is gone - you cannot mix varchar and integer in the IN clause.
Edit For wildcard searches you can use LIKE or ILIKE (for case-insensitive searches)
SELECT * FROM account WHERE
(trim(?) = '') IS NOT FALSE
OR user_name like ?
OR first_name like ?
OR last_name like ?
Using a prepared statement you would call it like this (note that you have to bind the same parameter four times)
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, searchString);
ps.setString(2, searchString);
ps.setString(3, searchString);
ps.setString(4, searchString );
try (ResultSet rs = ps.executeQuery()) {
// read data
}
}
You can replace this line of your java code :
+ (searchString == null || searchString.length == 0 ) ? "" : (" WHERE '" + searchString + "' IN (ID, USER_NAME, FIRST_NAME, LAST_NAME)")
It basically checks if searchString is empty, and adds the line only if it is not
This question already has an answer here:
Having a Column name as Input Parameter of a PreparedStatement
(1 answer)
Closed 7 years ago.
I am using PreparedStatement to select records from a table:
public static String getMemberInfo(String columnName, Integer memberId) {
String memberInfo = "";
String sql = "SELECT ? FROM member WHERE member_id = ?";
DatabaseConnector.setConn();
try(Connection conn = DatabaseConnector.getConn();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, columnName);
ps.setInt(2, memberId);
try(ResultSet rs = ps.executeQuery()) {
if(rs.next()) {
memberInfo = rs.getString(columnName);
}
}
} catch(SQLException se) {
se.printStackTrace();
}
return memberInfo;
}
When I use
SELECT " + columnName + " FROM member WHERE member_id = ?, it works.
But when I use
SELECT ? FROM member WHERE member_id = ?, it does not.
Where should ? be placed in prepared statements?
? is for input values (typically in the WHERE clause conditions).
? is not for selected columns.
Column name must be hard-coded, Only column values can be set using ?.
but you can set dynamic column name by doing something like this :
String sql = "SELECT "+ columnName +" FROM member WHERE member_id = ?";
So I have a method that looks up a foreign key in a database. If the foreign key does not exist it will add an entry into the database. Now what I am doing from that point after inserting the new record, is re-querying again to get the foreign key. Is this overkill or is this the right way to do this? Thanks
private String getTestType(TestResult testResult) {
String testTypeId = "";
String query = String.format("SELECT id FROM test_types WHERE " +
"name='%s'", testResult.getTestType());
try {
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
} else {
st = con.prepareStatement("INSERT INTO test_types (name, " +
"created_at) VALUES (?, ?)");
st.setString(1, testResult.getTestType());
st.setTimestamp(2, new java.sql.Timestamp(System
.currentTimeMillis()));
st.executeUpdate();
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
}
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("There was an issue getting and or creating " +
"test Type");
}
return testTypeId;
}
Since you are inserting a new row into DB, you have to do a query to get back the auto increment field(id). Currently they way you are doing is workable. But there are few alternatives in query:
Obtaining the id using last_insert_id():
rs = st.executeQuery("select last_insert_id() as last_id");
id= rs.getString("last_id");
Another approach can be doing the MAX over the id column of the table.
I believe these are will be much faster than your query as you are doing string comparison in where clause.