How to use dynamic table name in SELECT query using JDBC - java

I have 5 or table table to query from \
my syntax i like this
String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql2);
System.out.println("SQL before values are set "+sql2);
System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
// values are outputted correctly but are not getting set in the query
pst.setString(1, tblName);
pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);
while(rs2.next()){
String ID = rs2.getString("ID");
jLabel35.setText(ID);
jLabel37.setText(ID);
jLabel38.setText(ID);
// them print command is initiated to print the panel
}
The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"
When i output the sql using system.out.println(sql2);
values are not set in sql2

When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:
String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery();

String sqlStatment = "SELECT * FROM " + tableName + " WHERE Patient_ID = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sqlStatment);
preparedStatement.setint(1, patientId);
ResultSet resultSet = preparedStatement.executeQuery();

public void getByIdEmployer() throws SQLException {
Connection con = null;
try {
con = jdbcUtil.connectionDtls();
PreparedStatement ptst = con.prepareStatement(getById);
ptst.setInt(1, 4);
ResultSet res = ptst.executeQuery();
while (res.next()) {
int empid = res.getInt(1);
System.out.println(empid);
String name = res.getString(2);
System.out.println(name);
int salary = res.getInt(3);
System.out.println(salary);
String location = res.getString(4);
System.out.println(location);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.close();
}
}

Related

why I cannot sum all number between two rows?

I am trying to write a code that sum all the data in a column named AMOUNT between two rows in a column named DATA in a table named PERSON and I used the sum function and I use between function
and I got the following error:
java.sql.SQLSyntaxErrorException: Syntax error:
Encountered "BETWEEN" at line 1, column 45.
the code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
String sql = "SELECT SUM(AMOUNT) AS SUMAMOUNT " +
"FROM PERSON BETWEEN DATE=? AND DATE=?";
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Invoices",
"user1", "password");
ps = con.prepareStatement(sql);
ps.setString(1, jTextField1.getText());
ps.setString(2, jTextField2.getText());
rs = ps.executeQuery();
if (rs.next()) {
String sum = rs.getString("sumAmount");
jLabel3.setText(sum);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
Try something like this:
String sql = "SELECT SUM(AMOUNT) AS SUMAMOUNT FROM PERSON " +
"WHERE (col_name) between '2020-05-01 00:58:26' " +
"and '2021-06-18 19:53:17'";

I want to add a search in my sql database, function to get the name by the id creates an error

I have a music database so I'll need a search function, now when entering into the search bar, I get the error : "Invalid argument in JDBC call: parameter index out of range: 1"
public static Song getSongByName(String name)
{
String sql =
"SELECT songID FROM Song "+
"WHERE name = '?'; ";
Connection conn = Connections.getConnection();
Song erg = null;
try
{
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
ResultSet rs = pstmt.executeQuery();
rs.next();
int id = rs.getInt (1);
name = rs.getString (2);
erg = new SongImpl(id,name);
rs.close();
pstmt.close();
}
catch(SQLException exc)
{
System.err.println("Fehler: in SQL-Aufruf");
System.err.println("["+sql+"]");
exc.printStackTrace();
System.exit(6);
}
Connections.putConnection(conn);
return erg;
}
It seems like you are selecting just one column instead of two.
The correct SQL query would be:
SELECT songID, songName FROM Song WHERE name = '?';
Try this:
public static Song getSongByName(String name)
{
String sql =
"SELECT songID, songName FROM Song "+
"WHERE name = ?";
Connection conn = Connections.getConnection();
Song erg = null;
try
{
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
ResultSet rs = pstmt.executeQuery();
rs.next();
int id = rs.getInt(1);
String name = rs.getString(2);
erg = new SongImpl(id, name);
rs.close();
pstmt.close();
}
catch(SQLException exc)
{
System.err.println("Fehler: in SQL-Aufruf");
System.err.println("["+sql+"]");
exc.printStackTrace();
System.exit(6);
}
Connections.putConnection(conn);
return erg;
}
Let me know if that helped :)
Look onto examples https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Try to remove single quotes:
String sql =
"SELECT songID FROM Song "+
"WHERE name = ?; ";
You should use string parameters without quotes because your statement interpreted as a SQL query without parameters.

Prepared statement execute query error (com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException)

I have written a simple method to get a string out of the database:
public String getUserString(int id, String table, String column) {
String output = null;
try {
String sql = "SELECT ? FROM ? WHERE id=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setString(1, column);
preparedStatement.setString(2, table);
preparedStatement.setInt(3, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
} catch (SQLException e) {
e.printStackTrace();
}
return output;
}
But when I try to use it like this: coreMySQL.getUserString(1, "economy", "balance");
I get this error:
https://pastebin.com/BMAmN4Xh
You can't set table name and column names with setXxx method(s) for PreparedStatement. It can only be used to set the values.
However, you can do a simple String replace to substitute table names and column names, e.g.:
String query = SELECT <column> FROM <table> WHERE id=?;
String sql = query.replaceAll("<column>", column).replaceAll("<table>", table);
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
Define a query template as:
String queryTemplate = "SELECT %s FROM %s where id = ?;";
// Inside Function:
PreparedStatement preparedStatement = getConnection().prepareStatement(String.format(template, column, table));
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();

string parameter and SELECT prepared statement for sql in java

i have a problem >>
programming language: java
Data base: Mysql database
i write a java code for retrive the record from the database based on the data parameters comping from the method>>
the code is:
public static void Get_patient_data(String Hospital1_ID,String Hospital2_ID {
try {
Connection con = getConnection2();
PreparedStatement statement = (com.mysql.jdbc.PreparedStatement)
con.prepareStatement(
"SELECT PatientGender "+
"FROM patientcorepopulatedtable "+
"WHERE PatientID = Hospital1_ID LIMIT 1" );
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while( result.next()) {
System.out.print("the patient Gender is" +
result.getString("PatientGender"));
}
}
catch(Exception e) {
System.out.println("Error"+e);
}
}
As you see the problem is Hospital1_ID parameter .. is coming from the method and the patientID is a column in a table patientcorepopulatedtable ...
the = equal operator doesn't work.
Try this
String query =
"SELECT PatientGender FROM patientcorepopulatedtable "+
" WHERE PatientID = ? LIMIT ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, Hospital1_ID);
preparedStmt.setInt (2, 1);
preparedStmt.executeQuery();
you can do it this way
PreparedStatement statement = (com.mysql.jdbc.PreparedStatement)
con.prepareStatement(
"SELECT PatientGender FROM patientcorepopulatedtable "+
"WHERE PatientID = ? LIMIT 1");
statement.setString(1, Hospital1_ID);
ResultSet result = statement.executeQuery();
you can find more info here

JDBC does not Inserting data into mysql table

I have problem with inserting data into mysql table. JDBC doesnt inserting data into mysql table.
JDBC should get value from input "liczbaUzytkownikow" and "data from table form which contains informations about "termin" (Exactly: termin.nazwaObiektu, termin.adresObiektu, termin.dzien, termin.odKtorej and termin.doKtorej).
Here is code of this JDBC:
conn = ConnectionClass.Polacz();
ArrayList<Rezerwacja> rezerwacje = new ArrayList<Rezerwacja>();
PreparedStatement st = null;
ResultSet rs = null;
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
try
{
st = conn.prepareStatement(sql);
rs = st.executeQuery();
while(rs.next())
{
Rezerwacja rezerwacja = new Rezerwacja();
rezerwacja.setLiczbaUczestnikow(rs.getInt(1));
rezerwacja.setIdTermin(rs.getInt(2));
rezerwacje.add(rezerwacja);
}
}
catch(SQLException e)
{
System.out.println(e);
}
Any suggestions ?
You should use PreparedStatement to avoid sql injection attacks.
Furthermore your sql is wrong:
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
you cannot execute two different statements in a single batch.
In your case an Insert and an Update.
Create two PreparedStatement's:
String sql1 = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values (?,?)";
String sql2 = "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = ?";
PreparedStatement preparedStatement1 = con.prepareStatement(sql1);
preparedStatement1.setString(1, liczbaUczestnikow );
preparedStatement1.setInt(2, idTerminal);
PreparedStatement preparedStatement2 = con.prepareStatement(sql2);
preparedStatement2.setInt(1, idTerminal);
preparedStatement1.executeUpdate();
preparedStatement2.executeUpdate();

Categories

Resources