Get Array From List Of Rows? - java

I was curious on how to get a list of rows and add values from each row to an array in Java.
Here is what it looks like in PHP:
<?php
$result = mysql_query("SELECT * FROM names");
while($row = mysql_fetch_array($result)) {
// Get variables from this row and such
}
?>
I can't seem to find out how to do this in Java.
Resolution Found
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery("SELECT TOP 10 * FROM SalesLT.Customer");
while (res.next()) {
String firstName = res.getString("FirstName");
String lastName = res.getString("LastName");
System.out.println(" " + firstName + " " + lastName);
}

If you want to use pure JDBC you can follow the example from the JDBC tutorial:
public void connectToAndQueryDatabase(String username, String password) {
Connection con = DriverManager.getConnection(
"jdbc:myDriver:myDatabase", username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
}
But most people don't do this any more; you can, for example, use an ORM like hibernate to abstract the database a bit.

Related

Java to read different database tables

I try to receive content of tables using Java code. This is the basic code and I have an issue with it. I need the code to be flexible so it can read different tables (with different amount of rows/columns etc). I want the while loop to print all the columns in a particular table.
public class Main1 {
public static void main(String[] args) throws Exception {
Class.forName("org.gjt.mm.mysql.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql:address", "root", "");
String SQL = "select * from users";
ResultSet rs = Statement.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("querying SELECT * FROM users");
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1) System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue + " " + rsmd.getColumnName(i));
}
System.out.println("");
}
}
}
OK, you are probably better off using a PreparedStatement
consider
PreparedStatement ps = conn.prepareStatement (SQL);
rs = ps.executeQuery ();

How can i execute 2 Select Queries in Java?

I need your help there with my code I am working on eclipse. When I try to execute 2 Select Queries in Java it doesn't seem to work , I searched the internet but I couldn't find a solution. I need to execute 2 select because I need data from 2 tables I got in a database.
Table 1: questions
Table 2: selections
Well the first query seems to work fine as I can find my items as I should when I execute. The items from Table 2 throws me an execution that
"Column 'selid' not found. ". // Selid Column is on Table 2.
I am posting you the faulty code on bottom in case you can help me on this.
Thanks in advance.
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
//String connectionURL = "jdbc:mysql://127.0.0.1:3306/newData";// newData is the database
//Connection connection;
Connection conn=null;
String dbName="teddb";
res.setContentType("text/html");
res.setCharacterEncoding("utf-8");
PrintWriter out = res.getWriter();
//String dbUserName="root";
//String dbPassword="root";
try{
String qid = "";
String question = "";
String sel1 = "";
String sel2 = "";
String sel3 = "";
String correct = "";
String selid ="";
String sel="";
Connection dbCon;
Class.forName(driver);
dbCon = DriverManager.getConnection(dbURL);
ResultSet rs;
ResultSet rs2;
Statement stmt;
Statement stmt2;
stmt = dbCon.createStatement();
stmt2 = dbCon.createStatement();
String qry = "";
String qry2 = "";
qry = "select * from questions";
qry2 = "select * from selections";
rs = stmt.executeQuery(qry);
stmt = dbCon.prepareStatement(qry);
rs2 = stmt2.executeQuery(qry2);
stmt2 = dbCon.prepareStatement(qry2);
String[] columns = new String[] { "qid",
"question_text" , "selid" , "selection_text" ,};
Random rn = new Random();
int range = 2 - 1 + 1;
int randomNum = rn.nextInt(range) + 1;
out.println(randomNum);
while (rs.next()) {
for (int i = randomNum; i <= randomNum; i++) {
question = rs.getString(columns[1]);
sel1 = rs.getString(columns[2]);
sel2 = rs.getString(columns[3]);
}
}
PreparedStatement pstmt;
for (int z=1;z<=3;z++){
selid = String.valueOf(rs.getString(columns[2]));
pstmt = dbCon.prepareStatement(qry2 + " where qid = ? and selid ='z'");
pstmt.setString(1, qid);
rs2 = pstmt.executeQuery();
while (rs2.next()) {
for (int i = randomNum; i <= randomNum; i++) {
if (z==1)
sel1 = rs.getString(columns[3]);
else if (z==2)
sel2 = rs.getString(columns[3]);
else
sel3 = rs.getString(columns[3]);
}
}
}
out.println("<!DOCTYPE html>"+
"<html><body>"+
"<form method=\"post\" action=\"demoServlet\">"+
"<b><h1>Ερώτηση</h1></b> <br><br>"+
"<b><h1>"+question+" </h1></b> <br><br>"+
"<b> 1: </b> <input type=\"radio\" name=\"iscorrect\" value=\"" + sel1 + "\"/><br>"+
"<b> 2: </b> <input type=\"radio\" name=\"iscorrect\" value=\"" + sel2 + "\"/> <br>"+
"<b> 3: </b> <input type=\"radio\" name = \"iscorrect\" value=\"" + sel3 + "\"/><br><br>"+
"<br><input type=\"submit\" name=\"submit\" value=\"Απάντηση\"/>"+
"</form></body></html>");
dbCon.commit();
String msg=" ";
rs.close();
rs2.close();
stmt.close();
dbCon.close();
}
catch (Exception e){
out.println(e);
}
Concept is that i have 2 tables and iam making a form that the users answers some questions. Iam executing both tables and then iam trying to put the variables in to the form with submit. DoPost will take effect after DoGet in the same servlet.
Here is the example of the tables.
questions | selections
qid | question | qid | | selid | selection_text |correct
q1 | 1+1? | q1 1 5 0
q1 2 2 1 // true
q1 3 4 0
Change
rs = stmt.executeQuery(qry);
rs2 = stmt.executeQuery(qry2);
to
rs = stmt.executeQuery(qry);//first query
rs2 = stmt2.executeQuery(qry2);//second query

Operation not allowed after ResultSet closed (mysql, java)

I was stuck with the error , here my line number 42 is while(rs.next()){, please help me with this i am stuck at this for few hrs.
> Exception in thread "main" java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:937)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:872)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:740)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6326)
at removeStopwords.RemoveStopwords.main(RemoveStopwords.java:42)
This is my code:
package removeStopwords;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.StringTokenizer;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class RemoveStopwords {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/mydbv2";
// Database credentials
static final String USER = "root";
static final String PASS = "***";
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection conn = null;
Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
stmt = (Statement) conn.createStatement();
String sql;
ResultSet rs = null;
ResultSet rs2 = null;
ResultSet rs3 = null;
java.sql.PreparedStatement ps = null;
int event_id = 10;
sql = "SELECT id,text from tweet where event_id = " + event_id;
rs = stmt.executeQuery(sql);
String text = "";
Long id;
while (rs.next()) {
id = rs.getLong("id");
text = rs.getString("text");
System.out.println("tweet = " + text);
text = text.replaceAll("http[^\\s]+", "");
text = text.replaceAll("www[^\\s]+", "");
System.out.println("tweet after removal of links= " + text);
StringTokenizer st = new StringTokenizer(text);
while (st.hasMoreTokens()) {
String stopword = st.nextToken();
System.out.println("stopword : " + stopword);
sql = "SELECT * from stopwords WHERE word =" + '"'+stopword+'"';
rs2 = stmt.executeQuery(sql);
if (rs2.next()) {
text = text.replaceAll(stopword, "");
System.out.println("tweet after removing stopword = " + text);
}
sql = "SELECT * from filtertweet where tweet_id = " + id + "";
rs3 = stmt.executeQuery(sql);
if (!rs3.next()) {
sql = "INSERT INTO filtertweet VALUES(?,?)";
ps = conn.prepareStatement(sql);
ps.setLong(1, id);
ps.setString(2, text);
ps.executeUpdate();
}
}
}
stmt.close();
conn.close();
}
}
A Statement object can have only one active ResultSet, so when you execute rs2 = stmt.executeQuery(sql), the first ResultSet (rs) gets closed.
Create two Statement objects, one for rs and another for rs2.
Quoting the javadoc of Statement:
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
One ResultSet for one Statement is valid. When you are executing multiple queries use various Statements.
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection conn = null;
Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
stmt = (Statement) conn.createStatement();
String sql;
ResultSet rs = null;
ResultSet rs2 = null;
ResultSet rs3 = null;
java.sql.PreparedStatement ps = null;
int event_id = 10;
sql = "SELECT id,text from tweet where event_id = " + event_id;
rs = stmt.executeQuery(sql);
String text = "";
Long id;
while (rs.next()) {
id = rs.getLong("id");
text = rs.getString("text");
System.out.println("tweet = " + text);
text = text.replaceAll("http[^\\s]+", "");
text = text.replaceAll("www[^\\s]+", "");
System.out.println("tweet after removal of links= " + text);
StringTokenizer st = new StringTokenizer(text);
while (st.hasMoreTokens()) {
String stopword = st.nextToken();
System.out.println("stopword : " + stopword);
sql = "SELECT * from stopwords WHERE word =" + '"'+stopword+'"';
Statement stmt2 = conn.createStatement();
rs2 = stmt2.executeQuery(sql);
if (rs2.next()) {
text = text.replaceAll(stopword, "");
System.out.println("tweet after removing stopword = " + text);
}
sql = "SELECT * from filtertweet where tweet_id = " + id + "";
Statement stmt3 = conn.createStatement();
rs3 = stmt3.executeQuery(sql);
if (!rs3.next()) {
sql = "INSERT INTO filtertweet VALUES(?,?)";
ps = conn.prepareStatement(sql);
ps.setLong(1, id);
ps.setString(2, text);
ps.executeUpdate();
}
}
}
stmt.close();
conn.close();
}
JDBC does not allow you to close the Statement that created the ResultSet or to execute another query that creates a ResultSet using the same Statement. Create different Statement objects and Resultset objects, make sure to not use the same Statement objects to execute two different Resultset statements.

Get the number of the affected rows

I am trying to get the number of the affected records of this query SELECT mac, stop_name from behaviour where mac = ? with the use of the executeQuery. How can I get the number of the affected rows?
Code:
if (behaviourExist.next()) {
PreparedStatement prepared = con
.prepareStatement("SELECT mac, stop_name from behaviour where mac = ?");
prepared.setString(1, macD);
ResultSet rsBehav = prepared.executeQuery();
ArrayList<String> stopNameList = new ArrayList<String>();
while (rsBehav.next()) {
//int numberOfRows = rsBehav.getInt(1);
String stNa = rsBehav.getString("stop_name");
if (stNa.equals(nameShortestDistance)) {
stopNameList.add(stNa);
}
}
}
This is a read operation so it will not affect any row. If you want to get the number of row returned then you could do one of the below
Use a counter variable and increment it in the loop while (rsBehav.next())
Use a scrollable resultset
PreparedStatement prepared = con.prepareStatement(
"SELECT mac, stop_name from behaviour where mac = ?",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rsBehav = prepared.executeQuery();
rsBehav.afterLast();
int numRow = rsBehav.getRow();
rsBehav.beforeFirst();
Here numRow will give you number or row returned,
PreparedStatement prepared = con
.prepareStatement(
"SELECT (SELECT count(*) from where mac = ?),"
" mac, stop_name from behaviour where mac = ?");
prepared.setString(1, macD);
prepared.setString(2, macD);
ResultSet rsBehav = prepared.executeQuery();
ArrayList<String> stopNameList = new ArrayList<String>();
while (rsBehav.next()) {
int numberOfRows = rsBehav.getInt(1);
String stNa = rsBehav.getString("stop_name");
// ....
if (behaviourExist.next()) {
PreparedStatement prepared = con
.prepareStatement("SELECT mac, stop_name from behaviour where mac = ?");
prepared.setString(1, macD);
ResultSet rsBehav = prepared.executeQuery();
ArrayList<String> stopNameList = new ArrayList<String>();
int numberOfRows = 0;
while (rsBehav.next()) {
++numberOfRows;
String stNa = rsBehav.getString("stop_name");
if (stNa.equals(nameShortestDistance)) {
stopNameList.add(stNa);
}
}
}
Here the variable numberOfRows will increment each time the loop runs which will give you the total number of rows in the resultSet.

Passing array parameter in prepare statement - getting "java.sql.SQLFeatureNotSupportedException"

I am facing error java.sql.SQLFeatureNotSupportedException in my prepare statement. I am using Mysql database.
Below is my code.
class tmp {
public static void main(String arg[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/sample", "root", "root");
PreparedStatement pst = conn
.prepareStatement("select * from userinfo where firstname in(?)");
String[] Parameter = { "user1", "Administrator" };
Array sqlArray = conn.createArrayOf("VARCHAR", Parameter);
pst.setArray(1, sqlArray);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
For Mysql -
Setting array is not possible in Mysql.
Instead of that you can form a query for (?,?,..) in the loop and same way for setting values.
String[] Parameter = { "user1", "Administrator" };
String query = "select * from userinfo where firstname in (";
String temp = "";
for(i = 0; i < Parameter.length; i++) {
temp += ",?";
}
temp = temp.replaceFirst(",", "");
temp += ")";
query = query + temp;
PreparedStatement pst = conn.prepareStatement(query);
so query becomes
select * from userinfo where firstname in (?,?)
and pass values also using loop.
For Oracle -
ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor("CHAR_ARRAY", conn);
String[] Parameter = { "user1", "Administrator" };
java.sql.Array sqlArray = new oracle.sql.ARRAY(arrayDescriptor, conn, content);
.
.
pstmt.setArray(1, sqlArray);
Error message is very clear. And MySQL does not support custom data types.
Currently MySQL is supporting only:
Numeric Type
Date and Time Type
String Type
Or, you can use each of the input values as a set of values of IN function in MySQL.
Change your JAVA code as follows:
StringBuilder sbSql = new StringBuilder( 1024 );
sbSql.append( "select * from userinfo where firstname in(" );
for( int i=0; i < Parameter.length; i++ ) {
if( i > 0 ) sbSql.append( "," );
sbSql.append( " ?" );
} // for
sbSql.append( " )" );
PreparedStatement pst = conn.prepareStatement( sbSql.toString() );
for( int i=0; i < Parameter.length; i++ ) {
pst.setString( i+1, Parameter[ i ] );
} // for
ResultSet rs = pst.executeQuery();
Convert List to a comma separated String and use it.
Class Tmp {
public static void main(String arg[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/sample", "root", "root");
// Consider this list is already constructed
List<String> parameter = new ArrayList<String>();
parameter.add("user1");
parameter.add("Administrator");
String parameterStr = "'" + String.join("','", parameter) + "'";
PreparedStatement pst = conn.prepareStatement("select * from userinfo where firstname in(" + parameterStr + ")");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories

Resources