JDBC COUNT() a certain row how to get the result [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am very new to JDBC and I am practicing executing query's and statements.
try {
Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
Statement st = conn.createStatement();
String query = "SELECT COUNT(*) AS \"Number of suppliers\", city\r\n" +
"FROM supplier\r\n" +
"GROUP BY city\r\n" +
"ORDER BY city DESC\r\n";
//st.executeUpdate(query);
ResultSet rs = st.executeQuery(query);
while(rs.next()) {
System.out.println(rs.getString("supplierNum"));
System.out.println(rs.getString("city"));
space();
}
st.close();
conn.close();
}
I am trying to execute and print the results using SELECT COUNT(supplierNum) AS "Number of suplliers", cityFROM supplierGROUP BY city ORDER BY city DESC;
The console just terminate and nothing happens no error message nothing just a blank screen.
This is the table I am trying to access
CREATE TABLE supplier
(
supplierNum CHAR(2) NOT NULL,
name CHAR(10) NOT NULL,
status TINYINT(4) NOT NULL,
city VARCHAR(10) NOT NULL,
PRIMARY KEY (supplierNum)
);

You aliased the count column as "Number of suplliers", yet your JDBC code is trying to find supplierNum. Use consistent aliases everywhere to resolve this problem:
String query = "SELECT city, COUNT(*) AS supplierCnt " +
"FROM supplier " +
"GROUP BY city " +
"ORDER BY city DESC";
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("supplierCnt"));
System.out.println(rs.getString("city"));
space();
}

Related

How I properly prepare JDBC PreparedStatment? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I started to work at my own Minecraft plugin. I need database connection to do so. I try to execute query and I get errors that I can't find solutions for.
Here is the code of function that I'm using:
public void checkIfUserExists(String login, Connection connection) {
String query = "SELECT login FROM edvault.users WHERE login = ?";
try {
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, login);
ResultSet rs = statement.executeQuery();
if (!rs.next()){
String query2 = "INSERT INTO edvault.users (login) VALUES ?";
PreparedStatement statement2 = connection.prepareStatement(query2);
statement2.setString(1 , login);
int result = statement2.executeUpdate();
if (result != 1){
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "<DBINFO> ERROR OCCURRED WHILE INSERTING NEW USER" +
" TO DATABASE");
} else {
Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "<DBINFO> ADDED NEW USER TO DATABASE : LOGIN - "+
login);
}
} else
Bukkit.getConsoleSender().sendMessage("<DBINFO> USER ALREADY EXISTS IN DATABASE");
} catch (SQLException e) {
e.printStackTrace();
}
}
And here is the exception that console returns to me (this is exception for the first query, where login is xEdziu):
[22:26:21] [Server thread/WARN]: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'xEdziu' in 'where clause'
Replace
INSERT INTO edvault.users (login) VALUES ?
with
INSERT INTO edvault.users (login) VALUES (?)

java.sql.SLQException: Illegal operation on empty result set [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I got a login system in java and i want to get de user, password and type of user from database. But when i run the programe i got the folowing error: java.sql.SLQException: Illegal operation on empty result set
Code:
conn=MysqlConnect.ConnectDB();
String Sql="Select*from utilizador where Nome='" + Username +"' and Password='" + Password +"' and Permissao'" + Permissao + "'" ;
try{
pst=conn.prepareStatement(Sql);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(Sql);
int permissao = rs.getInt("Permissao");
String nome = rs.getString("Nome");
String password = rs.getString("Password");
if(rs.next()){
Your code has various issues:
You missed an = after and Permissao
From your code it seems you are looking for a user filtering by the following fields: Username, Password and Permissao, so you should have 3 variables defined
You are trying to access the ResultSet (using rs.getXXX) before selecting any rows. After the executeQuery method you "fill" a ResultSet but his index is not pointing to any valid "database rows" so you need to call "rs.next()" in order to move the index to the first row. Consecutive calls move the index ahead of 1 position every time until the ResultSet finishes.
Having said so, you should:
Use a prepared statement that prevents sql injection and other typo/character errors as it automatically escapes parameter values.
In the prepared statement use ? to define the parameters you'll need to set using s.set<TypeOfField>
Check if ResultSet has rows before using rs.get
Close connection, statement, and result set in the finally clause, so the resources will be closed either if there is or there is not an exception. Doing so you will prevent memory leak due to opened resources that you are not using anymore.
You should have 3 variable to perform the select: (I suppose)
Username of type String
Password of type String
Permissao of type int/Integer
Try using the following code, adapted to your needs.
Connection c = DB.dbConnect(null);
PreparedStatement s = null;
ResultSet rs = null;
try {
final String SQL = " Select * from utilizador where Nome=? and Password=? and Permissao = ? ";
s = c.prepareStatement(SQL);
int i = 1;
s.setString(i++, Username);
s.setString(i++, Password);
s.setInt(i++, Permissao);
rs = s.executeQuery();
if (rs.next()) {
int permissao = rs.getInt("Permissao");
String nome = rs.getString("Nome");
String password = rs.getString("Password");
}
} catch (SQLException e) {
// exception handler
} finally {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
}
try {
if (s != null)
s.close();
} catch (Exception e) {
}try {
if (c != null)
c.close();
} catch (Exception e) {
}
}
Bad looking, unreadable code.
Here's your problem:
String nome = rs.getString("Nome");
String password = rs.getString("Password");
You try to access values from the ResultSet before checking to see if it has any rows.
Clearly the issue is with your query which is lacking proper quotes and spaces. It should be
String Sql="Select * from utilizador where Nome = '" + Username +"' and Password='" + Password +"' and Permissao = '" + Permissao + "'" ;

com.microsoft.sqlserver.jdbc.SQLServerException: There are more columns in the INSERT statement than values specified in the VALUES clause [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have a problem and i dont know how to fix it . Iam getting this errors but i am not sure if this error apear cause i am trying to call 2 functions with extends
com.microsoft.sqlserver.jdbc.SQLServerException: There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1454)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:786)
at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:685)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1416)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:185)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:160)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeUpdate(SQLServerStatement.java:642)
at mylogin.Orders.executeSQLQuery(Orders.java:147)
at mylogin.Orders.Make_OrderActionPerformed(Orders.java:439)
at mylogin.Orders.access$100(Orders.java:23)
Here is my code that appear to having the problem (at mylogin.Orders.executeSQLQuery(Orders.java:147))
//execute the sql query REFRESH JTABLE
public void executeSQLQuery (String query,String message) {
Connection con =getConnection();
Statement stt;
Statement sttt;
try{
stt =con.createStatement();
sttt =con.createStatement();
// **1 error 147**
if(((stt.executeUpdate(query))==1) || ((sttt.executeUpdate(query)) )==1)
{
//refresh jtable data
DefaultTableModel model=(DefaultTableModel)jTable_Orders.getModel();
model = (DefaultTableModel)jTable_Prordes.getModel();
model.setRowCount(0);
show_Products_in_Jtable();
show_Orders_in_Jtable();
JOptionPane.showMessageDialog(null,"Data "+message+" Succefully");
}else{
JOptionPane.showMessageDialog(null,"Data Not "+message+ "Error");
}
}catch (Exception ex){
ex.printStackTrace();
}
}
Here is my code that appear to having the problem (at mylogin.Orders.Make_OrderActionPerformed)
private void Make_OrderActionPerformed(java.awt.event.ActionEvent evt) {
String query="INSERT INTO Orders(Pro_Id ,Pro_Name,Order_Quantity,Order_Date,Order_Id)VALUES ('"+Pro_Id.getText()+" ','"+Pro_Name.getText()+" ','"+Order_Quantity.getText()+" ,'"+Order_Date.getText()+" ,'"+Order_Id.getText()+" ') ";
executeSQLQuery(query,"Inserted");
}
and finnaly this point (at mylogin.Orders.access$100)
public class Orders extends javax.swing.JFrame {
/**
* Creates new form Orders
*/
public Orders() {
initComponents();
show_Products_in_Jtable();
show_Orders_in_Jtable();
}
i am stuck at this points for days any help ??? ty !!!
Your ommiting a this symbol ' after ,'"+Order_Date.getText()+"'
INSERT INTO Orders(Pro_Id ,Pro_Name,Order_Quantity,Order_Date,Order_Id)VALUES ('"+Pro_Id.getText()+" ','"+Pro_Name.getText()+" ','"+Order_Quantity.getText()+" ,'"+Order_Date.getText()+"' ,'"+Order_Id.getText()+" ') "
this is better
String query = " insert into Orders(Pro_Id ,Pro_Name,Order_Quantity,Order_Date,Order_Id)"
+ " values (?, ?, ?, ?, ?)";
PreparedStatement Stmt = conn.prepareStatement(query);
preparedStmt.setString (1, Pro_Id.getText());
preparedStmt.setString (2, Order_Quantity());
preparedStmt.setDate (3, Order_Quantity.getText());
preparedStmt.setBoolean(4, Order_Date.getText());
preparedStmt.setInt (5, Order_Id.getText());
Stmt.execute();
This is mistake:
INSERT INTO Orders(Pro_Id ,Pro_Name,Order_Quantity,Order_Date,Order_Id)VALUES ('"+Pro_Id.getText()+" ','"+Pro_Name.getText()+" ','"+Order_Quantity.getText()+" ,'"+Order_Date.getText()+" ,'"+Order_Id.getText()+" ') "

Invalid operation at current cursor position [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I made a Java Forum and im trying to search my sql table, when i click the button to finally search it (the name of the person) it comes up with a "Invalid Operation at Current Cursor Position" error.
Here'e my code for the search button. Please help me figure this out.
private void firstSearchActionPerformed(java.awt.event.ActionEvent evt) {
try{
String fname = searchText.getText();
Connection connect = DriverManager.getConnection("jdbc:derby://localhost:1527/Employees",
"users", "admin");
PreparedStatement pState = connect.prepareStatement("select * from WORKERS where First_Name = ?");
pState.setString(1,fname);
ResultSet rSet;
rSet = pState.executeQuery();
if(rs.next()){
int id_col = rSet.getInt("Employee_ID");
String id = Integer.toString(id_col);
String first = rSet.getString("First_Name");
String last = rSet.getString("Last_Name");
String job = rSet.getString("Title");
String hireDate = rSet.getString("Hire_Date");
textID.setText(id);
textFirstName.setText(first);
textLastName.setText(last);
textTitle.setText(job);
textHireDate.setText(hireDate);
}else{
JOptionPane.showMessageDialog(null, "Not in Database");
}
}catch(SQLException err){
JOptionPane.showConfirmDialog(employees.this, err.getMessage());
}
}
ResultSet rSet;
rSet = pState.executeQuery();
instead of
if(rs.next()){
use
if(rSet.next()){
Here resultset object is rSet not rs

can i write my Sql query in this way [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am wondering can i insert table name in this format
String update = "UPDATE ? SET Status = ? WHERE Name = ?";
stmt.setString(1,tableName);
stmt.setString(2,status);
stmt.setString(3,name);
same for insert and delete statements?
No.
The reason you place question marks in the query (aside from protection against SQL injection) is so that the database can prepare the statement once and use that prepared statement with different parameters. It wouldn't be able to prepare a statement if it doesn't know what table(s) you are using.
The short answer is no. But you can do it this way:
String update = "UPDATE " + tableName + " SET Status = ? WHERE Name = ?";
...
stmt.setString(1,status);
stmt.setString(2,name);
Be aware of the SQL injection though. Be sure your tableName comes from the secure source.
Normally, you would do this as shown below...
String sql = "UPDATE " + tableName " SET Status = ? WHERE Name = ?";
PreparedStatement stmt = null;
try {
stmt = connection.prepareStatement(sql);
stmt.setString(1, status);
stmt.setString(2, name);
stmt.executeUpdate();
} finally {
if (stmt != null) {
stmt.close();
}
}
No you cann't do this because you are definitely using a prepared statement. The reason you can not do this is PreparedStatement is pre-compiled so it needs the table which you are modifing (its data using DML) or structurally (using DDL). If you don't mention the table table name how the statement is going to be pre-compiled?
If you want you can use dynamic SQL but in that case you don't have to use PreparedStatement you can use it using a simpler implementation Statement.
Hope this is helpful !!

Categories

Resources