JDBC Discover row based on a value in column - java

Need help from you all in writing up this query.
I have two columns, X and Y.
I have found a value in column Y and I am trying to find its row number.
Alternatively, I was trying to do:
SELECT ID in COLUMN_NAME from TABLE_NAME WHERE COLUMN_NAME2 contains some value I have already retrieved!
private int findRow(int value) throws SQLException {
Connection mysqlConn = DriverManager.getConnection(DB_URL, USER, PASS);
try {
String query ="SELECT BUILDING FROM ALLBUILDINGS WHERE BUILDINGNUMBER = 'value'";
Statement st = mysqlConn.prepareStatement(query);
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
value = rs.getInt(value);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return value;
}
Can someone tell me how I could do either of the aforementioned?
Thanks in advance!

This should solve your problem.
private int findRow(int value) throws SQLException {
Connection mysqlConn = DriverManager.getConnection(DB_URL, USER, PASS);
try {
String query ="SELECT BUILDING FROM ALLBUILDINGS WHERE BUILDINGNUMBER = ?";
PreparedStatement st = mysqlConn.prepareStatement(query);
st.setInt(1,value);
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
value = rs.getString(1);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return value;
}

I assume you're not trying to find the row index, but instead what the value of the X column is, in the row where Y column = "some_value".
SELECT X FROM ALL_BUILDINGS WHERE Y = "some_value";
This will match all rows where the Y column is "some_value", and return a corresponding set of values from column X.

Related

How to hold MySQL query result in an int variable if possible

I want to know whether a table exist or not before creating another one is there any way of holding result in a variable after execution of command, i am using this code but it keeps giving only true even if table doesn't exists.
public static boolean checkBefore(){
boolean r = false;
try{
query = "SELECT COUNT(*)FROM information_schema.tables WHERE table_schema = 'sms' AND table_name = 'auth';";
con = connectsms();
st = con.createStatement();
ResultSet rs = st.executeQuery(query);
r = rs.next();
}catch(SQLException e){
JOptionPane.showMessageDialog(errorMsg,"Exeption Fount: "+e,"Opps! Exception Found in checkBefore()",JOptionPane.ERROR_MESSAGE);
}
System.out.println(r);
return r;
}
Every JDBC guide will show you that after executing a query, you need to call next() to advance to the next/first row, then call getter methods to retrieve the column values of that row.
Queries with aggregating functions (COUNT, MIN, MAX, etc) without a GROUP BY clause will always return exactly one row, so for those kinds of queries, you don't need to check the return value from next(). For pretty much all other queries, you do.
When calling JDBC methods that return resources, you should use try-with-resources to make sure those resource are cleaned up correctly.
Query string does not need to end with a ; semi-colon.
All that means that your code should be:
public static boolean checkBefore() {
String sql = "SELECT COUNT(*)" +
" FROM information_schema.tables" +
" WHERE table_schema = 'sms'" +
" AND table_name = 'auth'";
try ( Connection con = connectsms();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
) {
rs.next(); // exactly one row returned, so next() always returns true here
int count = rs.getInt(1); // get value from first column
System.out.println("count = " + count);
return (count != 0);
} catch (SQLException e) {
JOptionPane.showMessageDialog(errorMsg, "Exeption Fount: " + e,
"Opps! Exception Found in checkBefore()",
JOptionPane.ERROR_MESSAGE);
return 0;
}
}
Change r = rs.next(); to rs.next(); and then add r = rs.getInt(1) > 0; and it will work.
This is the query that worked for me:
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'databse_name';
and the code that i am using and is working correct:
public static boolean checkBefore(){
boolean result = false;
try{
query = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'sms'";
con = connectsms();
st = con.createStatement();
ResultSet rs = st.executeQuery(query);
result = rs.next();
System.out.println();
}catch(SQLException e){
JOptionPane.showMessageDialog(errorMsg,"Exeption Fount: "+e,"Opps! Exception Found in checkBefor()",JOptionPane.ERROR_MESSAGE);
}
try{
con.close();
}
catch(SQLException e){JOptionPane.showMessageDialog(errorMsg,"Exeption Fount: "+e,"unable to close connection",JOptionPane.ERROR_MESSAGE); }
System.out.println(result);
return result;
}

Getting newly inserted id as empty string when I add SET NAMES to my insert statement

I have following program which insert emoji and any text to my MySql AWS Database. I was unable to add Emojis in my MySql database, but then i fixed this problem by changing collation and adding this-> SET NAMES utf8mb4; query before my previous insert query but now i am unable to get last inserted id from it. what should i do in order to insert emoji as well as to get last inserted id from it.
Here is my code.
public static JSONObject emoji(String comment) {
JSONObject json = new JSONObject();
Connection con = null;
PreparedStatement stmt = null;
String newInsertId = "";
try {
BasicDataSource bds = DBConnection.getInstance().getBds();
con = bds.getConnection();
String query = "SET NAMES utf8mb4; insert into emojis set message = '" + comment + "';";
stmt = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
if (stmt.executeUpdate() > 0) {
json.put("success", 1);
}
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
newInsertId = rs.getString(1); //giving empty values cause of that SET NAMES utf8mb4; query
}
System.out.println(newInsertId); //empty
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
DbUtils.close(con);
DbUtils.close(stmt);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
}
static int create() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 2.建立连接
conn = JdbcUtils.getConnection();
// conn = JdbcUtilsSing.getInstance().getConnection();
// 3.创建语句
String sql = "insert into user(name,birthday, money) values ('name2 gk', '1987-01-01', 400) ";
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//参数2最好写上,虽然Mysql不写也能获取但是不代表别的数据库可以做到
ps.executeUpdate();
rs = ps.getGeneratedKeys();
int id = 0;
if (rs.next())
id = rs.getInt(1);
return id;
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
——————————————————————————————————————————————————————
Focus on this 'Statement.RETURN_GENERATED_KEYS'

Query and Update

I am trying to query a database records and update at the same time.
the field UserSerial in database needs to be increased by 1 to create a kind of internal serial number, I am using a variable name counter to do that.
When I run the code, I see that the highest counted number (number of records in database) is stored in the UserSerial.
Can someone have a look at my code and tell me what my mistake is?
public class UsersMenu_Fill_usersSerialNumber {
PreparedStatement statement;
PreparedStatement statementUPD;
private Connection con = null;
private Connection conUPD = null;
private String sql_qry;
private String sql_upd;
int counter = 0;
public void UsersMenu_Fill_usersSerialNumber(){
DBModule.ConnectDataBase.ConnectDataBase_Method();
con = DBModule.ConnectDataBase.ConnectDataBase_Method();
conUPD = DBModule.ConnectDataBase.ConnectDataBase_Method();
sql_qry = "select UserSerial from users";
sql_upd = "update users set UserSerial = ?";
try {
statement = con.prepareStatement(sql_qry);
statementUPD = conUPD.prepareStatement(sql_upd);
ResultSet rslt = statement.executeQuery();
while (rslt.next()){
String FieldToChange = rslt.getString("UserSerial");
int FieldToChange_int = Integer.parseInt(FieldToChange);
counter++;
FieldToChange_int = counter;
statementUPD.setString(1, String.valueOf(FieldToChange_int));
statementUPD.executeUpdate();
}
statement.close();
} catch (SQLException ex) {
Logger.getLogger(UsersMenu_Fill_usersSerialNumber.class.getName ()).log(Level.SEVERE, null, ex);
}
}
}
So, there's a couple of things you need to know/do. Firstly, you need to pull back a unique identifier for your row, and use that identifier in your update sql to indicate which row should be updated. I'm going to assume that you've got an ID column on your users table, and use that.
Secondly, you need to retrieve that ID in your select statement, rather then the userSerial which you don't actually need to retrieve.
Then as you loop through, you need to uniquely update the value based on a where clause in the update statement that you specify with your unique id, ID.
I updated your function only to make demonstrate. I did not test this at all, it's just a guide to get you moving.
public void UsersMenu_Fill_usersSerialNumber(){
DBModule.ConnectDataBase.ConnectDataBase_Method();
con = DBModule.ConnectDataBase.ConnectDataBase_Method();
conUPD = DBModule.ConnectDataBase.ConnectDataBase_Method();
sql_qry = "select ID from users";
sql_upd = "update users set UserSerial = ? where ID = ?";
try {
statement = con.prepareStatement(sql_qry);
statementUPD = conUPD.prepareStatement(sql_upd);
ResultSet rslt = statement.executeQuery();
while (rslt.next()){
Long id = statement.getLong("ID");
counter++;
statementUPD.setString(1, String.valueOf(counter));
statementUPD.setLong(2, String.valueOf(id));
statementUPD.executeUpdate();
}
statement.close();
} catch (SQLException ex) {
Logger.getLogger(UsersMenu_Fill_usersSerialNumber.class.getName ()).log(Level.SEVERE, null, ex);
}
}

Retrieving data from database and increment by one

I am trying to retrieve a data (ID No.) from a database (MySQL) and add it by one. However, when I try to put this code below, when I try to build it, the form doesn't show up. But when I try to remove the Connection cn line, the form with finally show up. I had another project with this code it it worked perfectly fine. I'm not sure why its not working on this one.
public Abstract() throws Exception {
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
initComponents();
Statement st = null;
ResultSet rs;
try {
String sql = "SELECT ID from bidding_abstractofprices";
st = cn.prepareStatement(sql);
rs = st.executeQuery(sql);
while(rs.next()){
int id = Integer.parseInt(rs.getString("ID")) + 1;
lblTransacID.setText(String.valueOf(id));
}
}catch (Exception ex){
}
}
What it looks like you are trying to do is to get the ID field value from the last record contained within the bidding_abstractofprices Table contained within your Database and then increment that ID value by one (please correct me if I'm wrong). I don't care why but I can easily assume. Here is how I might do it:
public Abstract() throws Exception {
// Allow all your components to initialize first.
initComponents();
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
Statement st = null;
ResultSet rs;
try {
String sql = "SELECT * FROM bidding_abstractofprices ORDER BY ID DESC LIMIT 1;";
st = cn.prepareStatement(sql);
rs = st.executeQuery(sql);
int id = 0;
while(rs.next()){
id = rs.getInt("ID") + 1;
}
lblTransacID.setText(String.valueOf(id));
rs.close();
st.close();
cn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}

How do you access the value of an SQL count () query in a Java program

I want to get to the value I am finding using the COUNT command of SQL. Normally I enter the column name I want to access into the getInt() getString() method, what do I do in this case when there is no specific column name.
I have used 'AS' in the same manner as is used to alias a table, I am not sure if this is going to work, I would think not.
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) FROM "+lastTempTable+") AS count");
while(rs3.next()){
count = rs3.getInt("count");
}
Use aliases:
SELECT COUNT(*) AS total FROM ..
and then
rs3.getInt("total")
The answers provided by Bohzo and Brabster will obviously work, but you could also just use:
rs3.getInt(1);
to get the value in the first, and in your case, only column.
I would expect this query to work with your program:
"SELECT COUNT(*) AS count FROM "+lastTempTable+")"
(You need to alias the column, not the table)
I have done it this way (example):
String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"r#r.com"'";
int count=0;
try {
ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
while(rs.next())
count=rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//...
}
<%
try{
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
if(con == null) System.out.print("not connected");
Statement st = con.createStatement();
String myStatement = "select count(*) as total from locations";
ResultSet rs = st.executeQuery(myStatement);
int num = 0;
while(rs.next()){
num = (rs.getInt(1));
}
}
catch(Exception e){
System.out.println(e);
}
%>
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
count = rs3.getInt("count");
It's similar to above but you can try like
public Integer count(String tableName) throws CrateException {
String query = String.format("Select count(*) as size from %s", tableName);
try (Statement s = connection.createStatement()) {
try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
Preconditions.checkArgument(resultSet.next(), "Result set is empty");
return resultSet.getInt("size");
}
} catch (SQLException e) {
throw new CrateException(e);
}
}
}

Categories