why I cannot sum all number between two rows? - java

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'";

Related

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.

Java ResultSet Column count is always 1

I want to show the Column numbers of a table but it always shows the number 1. I have written the code below:
Class.forName(JDBC_DRIVER);
java.sql.Connection con=DriverManager.getConnection(DB_URL,USER,PASS);
try (Statement stmt = (Statement) con.createStatement()) {
String sql;
sql = "SELECT count(*) FROM information_schema.columns WHERE
table_name=\"my_b\"";
try (
ResultSet rs = stmt.executeQuery(sql)) {
int columCount = rs.getMetaData().getColumnCount();
System.out.println("Column number is: "+columCount);
}
stmt.close();
con.close();
Where is the error ?
First, you haven't needed Class.forName to load your JDBC drivers in a long time. Second, you are selecting a value but you are reading metadata. Third, when using try-with-resources you don't need explicit close calls (and your Connection should be closed in a finally, for example). Finally, use PreparedStatement and bind parameters. Like,
java.sql.Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
String query = "SELECT count(*) FROM information_schema.columns WHERE table_name=?";
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setString(1, "my_b");
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
int columCount = rs.getInt(1);
System.out.println("Column number is: " + columCount);
} else {
System.out.println("No rows");
}
}
} finally {
con.close();
}
You are not retrieving the result of the query, instead you are asking the result set metadata how many columns the result set has. And as your query only produce a single column (ie COUNT(*)), the result of ResultSetMetaData.getColumnCount() is 1, and that value is correct.
If you want to get the result of the query, you need to get it from the result set:
try (ResultSet rs = stmt.executeQuery(sql)) {
if (rs.next()) {
int columnsNumber = rs.getInt(1);
System.out.println("Column number is: "+columnsNumber );
}
}
The problem is that ResultSet.getColumnCount returns the number of columns in the query's result set, not the number of columns in a table.
If you are trying to get a count of columns on a table, the query you have is correct. You just need to retrieve the result of the query, rather than its metadata.
String sql = "SELECT count(*) FROM information_schema.columns WHERE table_name=\"my_b\"";
try (
ResultSet rs = stmt.executeQuery(sql));
rs.next();
int columCount = rs.getInt(1);
System.out.println("Column number is: " + columCount);
}
Class.forName(JDBC_DRIVER);
java.sql.Connection con=DriverManager.getConnection(DB_URL,USER,PASS);
try (Statement stmt = (Statement) con.createStatement()) {
String sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'database_name' AND table_name = 'table_name'"
try (
ResultSet rs = stmt.executeQuery(sql)) {
//int columCount = rs.getMetaData().getColumnCount();
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
System.out.println("Column number is: "+columnsNumber );
}
stmt.close();
con.close();
Try SELECT * FROM information_schema.columns WHERE table_name=\"my_b\"
Just omit the count(*) since this returns a single result, while you are looking for all columns.

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

Get the query plan using jdbc PreparedStatement on sql server

Using Statment, resultSet.getObject returns query plan as xml
Connection conn = getConnection();
String query = " SET SHOWPLAN_XML on ";
Statement st = conn.createStatement();
boolean execute=st.execute(query);
log.info("execute status {} " , execute);
query = " SELECT ATMPROFILES.TERMID as COLUMNID, ATMPROFILES.TERMID as COLUMNNAME FROM ATMPROFILES (NOLOCK) "
+ " WHERE Authprocessname = 'ATMST' "
+ "ORDER BY ATMPROFILES.TERMID ";
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
Object object = rs.getObject(1);
log.info("Query Plan {} ", object);
}
But If I execute the same through PreparedStatement, it returns actual result insteadof QueryPlan
Connection conn = getConnection();
String query = " SET SHOWPLAN_XML on ";
PreparedStatement ps = conn.prepareStatement(query);
boolean execute = ps.execute();
log.info("execute status {} " , execute);
query = " SELECT ATMPROFILES.TERMID as COLUMNID, ATMPROFILES.TERMID as COLUMNNAME FROM ATMPROFILES (NOLOCK) "
+ " WHERE Authprocessname = 'ATMST' "
+ "ORDER BY ATMPROFILES.TERMID ";
ps=conn.prepareStatement(query);
execute=ps.execute();
log.info("execute status {} " , execute);
ResultSet rs = ps.getResultSet();
while(rs.next())
{
Object object = rs.getObject(1);
// here it returns selected object
log.info("Query Plan {} ", object);
}
Any idea to acheive this via PreparedStatement.
I haven't found any reference why executing SET SHOWPLAN_XML ON as a prepared statement will not work; however, you should get the desired results when you run this statement directly and your actual query as a prepared statement. In code:
Connection conn = getConnection();
String showplanQuery = "SET SHOWPLAN_XML ON";
Statement st = conn.createStatement();
st.execute(showplanQuery);
String actualQuery = "SELECT ATMPROFILES.TERMID FROM ATMPROFILES (NOLOCK) ";
PreparedStatement ps=conn.prepareStatement(actualQuery);
ps.execute();
ResultSet rs = ps.getResultSet();
while(rs.next())
{
Object object = rs.getObject(1);
// should log the query plan
log.info("Query Plan {} ", object);
}
Hope that helps.

How to use dynamic table name in SELECT query using JDBC

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

Categories

Resources