Passing a mysql query to the database using a java program - java

I am new to mysql and I am trying to connect to the database using a Java Program and I am passing a mysql query.
public class dbconnect {
public static void main(String[] args) throws SQLException,ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase?user=root&password=root");
Statement st = conn.createStatement();
int custid= 0;
String myname = null;
String query = "select name from groups where customer_id = 2;";
//This query has a problem can anyone help me fix it.
System.out.println(query);
ResultSet rs1 = st.executeQuery(query);
System.out.println("after query");
while (rs1.next()){
custid = rs1.getInt("customer_id");
myname = rs1.getString("name");
System.out.println(myname);
System.out.println(custid);
}
}
}
I am passing a query "select name from groups where customer_id = 2" .
Here "name" is a coloumn,"groups" is a table and "customer_id" is another column. In the program when I give this query(no typos) I get the following error
Exception in thread "main" java.sql.SQLException: Column 'customer_id' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1144)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2815)
at com.memoir.client.widgets.memogen.dbconnect.main(dbconnect.java:61)
I have checked with the table , customer_id is present in the table . They are no spelling mistakes also .Even then it says that customer_id column is not found .
Can anyone help me fix it.

The query needs to be:
String query = "select name, customer_id from groups where customer_id = 2;";

Honestly it doesn't make any sense, your query is
String query = "select name from groups where customer_id = 2;";
and you expect to get customer_id ??
as you are already passing customer_id in where clause you don't need to get it back again from db.
String query = "select customer_id,name from groups where customer_id = 2;";
The above would work with your current code .

You are accessing only name column in query and you are try to get "customer_id" in while loop from result set
while (rs1.next()){
custid = rs1.getInt("customer_id"); // **error is here - remove this line or change your query**
myname = rs1.getString("name");
System.out.println(myname);
System.out.println(custid);
}

Your problem is that you are trying to get an invalid column ("cutomer_id") from the result set which contains only the "name" column.
To resolve this you have to select also the "customer_id" in your query:
"select name, customer_id from groups where customer_id = 2";

custid = rs1.getInt("customer_id");
you result set does not have customer_id
Include that too in your query

try this
String mysqlquery = "select name, customer_id from groups where customer_id=2";

Related

select JDBC query not retrieving records in order

I am trying to fetch records from oracle db. I have a select query which has an order by clause implemented. Now when I fire the query on the toad i get the results in correct order. i.e the order of the records at 10:00 AM is like
Record 1, Record 2,Record 3 and at 10:05 its Record 1, Record 2, Record 3. This is what i need.
Now when iam fetching it through java code, JDBC . I try to iterate the resultset, but here at 10:05 am I am getting the order like Record 2, Record 1, Record 3. Due to this when i am adding the records to the arraylist the order is not mantained.
I dont want to sort the records of arraylist after adding.
Can someone please let me know why using jdbc the records are not fetched in the order we can see using toad ?
Sample code
try{
List<TestObjVO> testResults = new ArrayList<TestObjVO>();
double statusValue = 0;
//Connection code
pstmt = conn.prepareStatement(QUERY);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
testObj = new TestObjVO();
String date = rs.getString(1);
String status = rs.getString(2);
String svc_nm= rs.getString(3);
if("SUCCESS".equalsIgnoreCase(status)){
statusValue = 1;
}else if("ERROR".equalsIgnoreCase(status)){
statusValue = -1;
}
testObj.setTime(date);
testObj.setStatus(statusValue);
testObj.setSvc_nm(svc_nm);
testResults.add(testObj);
}
SELECT query
SELECT to_char(PROBING_DATE,'DD-MM-YYYY HH24:MI:SS') AS PROBING_DATE, STATUS, SERVICE_NAME FROM TABLE_NAME WHERE PROBING_DATE >= (sysdate-30/1440) ORDER BY PROBING_DATE,SERVICE_NAME
Table
create table TABLE_NAME(
probing_date TIMESTAMP(6) not null,
status VARCHAR2(8) not null,
service_name VARCHAR2(128) not null
)
Change your select to something like this:
SELECT to_char(PROBING_DATE,'DD-MM-YYYY HH24:MI:SS') AS PROBING_DATE_STR,
PROBING_DATE,
STATUS,
SERVICE_NAME
FROM TABLE_NAME
WHERE PROBING_DATE >= (sysdate-30/1440)
ORDER BY PROBING_DATE,SERVICE_NAME;
Note there's an extra field returned and is the raw TIMESTAMP field.

Invalid operation for read only resultset: updateString

Following is my code(Re-constructed) which select & update STATUS field depending upon the conditions. (Using Servlets, Oracle as Backend and JDBC driver)
ResultSet rs=null;
String query = "select A.NAME, A.ADDRESS, A.STATUS, B.CLASS from TABLE_ONE A, TABLE_TWO B where A.STATUS='N'";
pstmt = con.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = pstmt.executeQuery();
while(rs.next())
{
String name = rs.getString("NAME");
String address = rs.getString("ADDRESS");
String class = rs.getString("CLASS");
String msg = //Other statements to check what status to be set
if(msg.equals("OK"))
rs.updateString("STATUS", "S");
else
rs.updateString("STATUS", "E");
rs.updateRow();
}
I am getting the error while updating:
java.sql.SQLException: Invalid operation for read only resultset: updateString
Any suggestions will be appreciated.
Update 1:
The same code was working when select statement was selecting data from single table, so is there any issue when selecting data from two tables in single query?
[Note: As #javaBeginner has mentioned in comments it will work only for one table.]
The following limitations are placed on queries for enhanced result sets. Failure to follow these guidelines will result in the JDBC driver choosing an alternative result set type or concurrency type.
To produce an updatable result set (from specification):
A query can select from only a single table and cannot contain any join operations.
In addition, for inserts to be feasible, the query must select all non-nullable columns and all columns that do not have a default value.
* A query cannot use "SELECT * ". (But see the workaround below.)
* A query must select table columns only. It cannot select derived columns or aggregates such as the SUM or MAX of a set of columns.
To produce a scroll-sensitive result set:
A query cannot use "SELECT * ". (But see the workaround below.)
A query can select from only a single table.
Try This :
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
//Execute a query
String sql = "select A.NAME, A.ADDRESS, A.STATUS, B.CLASS from TABLE_ONE A, TABLE_TWO B where A.STATUS='N'";
ResultSet rs = stmt.executeQuery(sql);
//Extract data from result set
rs.beforeFirst();
while(rs.next())
{
String name = rs.getString("NAME");
String address = rs.getString("ADDRESS");
String class = rs.getString("CLASS");
String msg = //Other statements to check what status to be set
if(msg.equals("OK"))
rs.updateString("STATUS", "S");
else
rs.updateString("STATUS", "E");
rs.updateRow();
}
Just changed Prepared statement to create statement
SELECT * makes the resultSet readonly. SELECT COLUMN_NAME makes it updatable.
So instead of SELECT * FROM TABLE use SELECT COLUMN1, COLUMN2, ... FROM TABLE.

PostgreSQL: Update my user table via Java

In PostgreSQL user is a reserved keyword that is used in an internal table, however I also have a separate user table in my own database that I need to use. Whenever I try to execute INSERT or UPDATE statements on the table, it generates the following error: The column name 'id' was not found in this ResultSet.
This is the Java code I am currently using:
PreparedStatement stat1 = conn.prepareStatement("SELECT id FROM user;");
PreparedStatement stat2 = conn.prepareStatement("UPDATE user SET date_created = ? , last_updated = ? , uuid = ? WHERE id = ?;");
ResultSet rs = stat1.executeQuery();
while(rs.next()){
UUID uuid = UUID.randomUUID();
String tempId = uuid.toString();
stat2.setTimestamp(1, curDate);
stat2.setTimestamp(2, curDate);
stat2.setString(3, tempId);
stat2.setLong(4,rs.getLong("id"));
stat2.executeUpdate();
}
So my question is, how could I insert or update the values in my personal user table without interfering with the keyword restriction?
Use this:
prepareStatement("UPDATE \"user\" set date_created = ?")
Or, better yet, rename your user table to something else, like users:
ALTER TABLE "user" RENAME TO users;
Escape the table name like this
select * from "user";

Java, MySQL updating table using ID (primary key)

I have a program in which working with MySql and Java JDBC.
My question is:
I have a table (TEMP) with ID as only 1 column and another table with user personal details like ID, name, age etc..
Im trying to retrieve the ID from TEMP table and update unfilled information like name, age, address etc in USER table.
This is the query I wrote:
update m_auth_info
set name = '"+name+"',
addr = '"+addr+"',
email = '"+email+"',
affiliation = '"+affil+"',
status = '"+1+"'
where a_id = '"+ResultSet+"'";
and when my getIdMethod retrieves ID into ResultSet from TEMP table. I couldn't able to update USER TABLE.
But it works if I give ID directly.. example.
update m_auth_info
set name = '"+name+"',
addr = '"+addr+"',
email = '"+email+"',
affiliation = '"+affil+"',
status = '"+1+"'
where a_id = '"+8989+"'";
Please tell me if I have to write which step to write in my getIdMethod, so that ill get the value into ResultSet.
int id=0;
String sql = "Select ID from Temp";
ResultSet rs = statement.executeQuery(sql);
while(rs.next(){
id = rs.getInt(1);
/* pass your update query here and use like this it should work for you
update m_auth_info set name = '"+name+"',
addr = '"+addr+"', email = '"+email+"',
affiliation = '"+affil+"', status = '"+1+"' where a_id = '"+id+"'";*/
}
I believe what you are trying to do is to get the result from ResultSet, which you can do with something rs.getLong(0), your ResultSet variable.getYourIdType(0) or columnName

PreparedStatement not returning ordered ResultSet

I am having some problems and I'm sure it's something stupid.
So I have a query like
SELECT name, id, xyz FROM table ORDER BY ?
then later down the road setting the ? doing a
ps.setString(1, "xyz");
I am outputting the query and the value of xyz in the console. When I loop through the ResultSet returned from the PreparedStatement the values are not in the correct order. They are in the returned order as if I had left the ORDER BY clause off. When I copy/paste the query and the value into TOAD it runs and comes back correctly.
Any ideas to why the ResultSet is not coming back in the correct order?
The database will see the query as
SELECT name, id, xyz FROM table ORDER BY 'xyz'
That is to say, order by a constant expression (the string 'xyz' in this case). Any order will satisfy that.
? is for parameters, you can't use it to insert column names. The generated statements will look something like
SELECT name, id, xyz FROM table ORDER BY 'xyz'
so that your entries are sorted by the string 'xyz', not by the content of column xyz.
Why not run:
ps.setInteger(1, 3);
Regards.
EDIT: AFAIK Oracle 10g supports it.
PreparedStatement placeholders are not intend for tablenames nor columnnames. They are only intented for actual column values.
You can however use String#format() for this, that's also the way I often do. For example:
private static final String SQL_SELECT_ORDER = "SELECT name, id, xyz FROM table ORDER BY %s";
...
public List<Data> list(boolean ascending) {
String order = ascending ? "ASC" : "DESC";
String sql = String.format(SQL_SELECT_ORDER, order);
...
Another example:
private static final String SQL_SELECT_IN = "SELECT name, id, xyz FROM table WHERE id IN (%s)";
...
public List<Data> list(Set<Long> ids) {
String placeHolders = generatePlaceHolders(ids.size()); // Should return "?,?,?..."
String sql = String.format(SQL_SELECT_IN, placeHolders);
...
DAOUtil.setValues(preparedStatement, ids.toArray());
...
The database will see the query like this
SELECT name, id, xyz FROM table ORDER BY 'xyz'
I think you should add more variable like order_field and order_direction
I assume you have a method like below and I give you an example to solve it
pulbic List<Object> getAllTableWithOrder(String order_field, String order_direction) {
String sql = "select * from table order by ? ?";
//add connection here
PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
ps.setString(1,order_field);
ps.setString(2,order_direction);
logger.info(String.valueOf(ps)); //returns something like: com.mysql.jdbc.JDBC4PreparedStatement#a0ff86: select * from table order by 'id' 'desc'
String sqlb = String.valueOf(ps);
String sqlc = sqlb.replace("'"+order_field+"'", order_field);
String sqld = sqlc.replace("'"+order_direction+"'", order_direction);
String[] normQuery = sqld.split(":");
ResultSet result = conn.createStatement().executeQuery(normQuery[1]);
while(result.next()) {
//iteration
}
}

Categories

Resources