How do i make my program read a Set value from the database one word by one word.
import java.util.*;
import java.sql.*;
public class SetProblem {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
Set<String> nums = new HashSet<>();
nums.add("1");
nums.add("2");
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:src/database/set.db");
st = con.createStatement();
//st.execute("create table data(word, synonyms);");
//st.executeUpdate("insert into data values('figure', '"+nums+"');");
rs = st.executeQuery("select * from data;");
Set<String> set = new TreeSet<>();
while(rs.next())
{
set.add(rs.getString(2));
}
for(String s:set)
{
System.out.print(s + "");
}
}
catch(ClassNotFoundException e)
{
System.out.println("Driver not found");
}
catch(SQLException s)
{
System.out.println("wrong sql command");
}
}
}
my problem is that it prints [1, 2] instead of
1
2
which i want. How can i achieve this?
You're inserting one row, but what you want (I think) is to insert two rows. You see [1, 2] because it is exactly what you're inserting in the second column (you're forcing a nums.toString()).
Here the code I think you were looking for:
//...
Set<String> nums = new HashSet<>();
nums.add("1");
nums.add("2");
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:src/database/set.db");
st = con.createStatement();
//st.execute("create table data(word, synonyms);");
//for(String i: nums) //HERE YOU NEED TO CYCLE
// st.executeUpdate("insert into data values('figure', '"+i+"');");
rs = st.executeQuery("select * from data;");
Set<String> set = new TreeSet<>();
while(rs.next())
{
set.add(rs.getString(2));
}
for(String s:set)
{
System.out.print(s + "");
}
}
//...
Related
I can't find the reason why this piece of code when run for a long time produces an out of memory heap error. It runs constantly for 1-2 days before crashing. Can anyone see anything?
I only call a static function from another class that should not keep any resources open and then the mysql stuff but I close them all.
note: some of the variable names were changed.
public class Application {
public static void main(String ...args) throws InterruptedException, IOException {
Data.connectDb(); //init
try {
List<Integer> written = new ArrayList<>();
Connection con = Data.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM table2 LIMIT 500");
while (rs.next()) {
Integer mId = rs.getInt("mId");
written.add(mId);
}
Map<Integer,String> bs = new HashMap<>();
rs = st.executeQuery("SELECT * FROM b");
while (rs.next()) {
bs.put(rs.getInt("bId"),rs.getString("name"));
}
st.close();
rs.close();
while (true) {
List<String> abers = new ArrayList<>();
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM table1 WHERE enabled = 1");
while (rs.next()) {
String email = rs.getString("email");
abers.add(email);
}
rs.close();
st.close();
ArrayList<Map> abs = Aber.getAbs(false);
ArrayList<Map> toDispatch = new ArrayList<>();
arbs.forEach((ab) -> {
Integer mId = (Integer) ab.get("mId");
if (!written.contains(mId)) {
written.add(mId);
toDispatch.add(arb);
Pair hLine = (Pair) ab.get("hLine");
Pair dLine = (Pair) ab.get("dLine");
Pair aLine = (Pair) ab.get("aLine");
//todo write it to the database not caring if it's already there as we have a unique constraint
try (Statement st2 = con.createStatement()) {
String sql = "INSERT INTO table1")";
st2.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
if (toDispatch.size() >0) {
Email email = new Email();
abes.forEach(arber -> email.addRecipient(aber, aber, Message.RecipientType.BCC));
String HTML = "<h3>Dear subscribers</h3>";
email.setTextHTML(HTML);
new Mailer(
new ServerConfig("mail.name.com", 587, "info#mm.com", "mmpass"),
TransportStrategy.SMTP_TLS
).sendMail(email);
}
Thread.sleep(600000);
}
} catch (SQLException sqle) {
System.out.println(sqle.getMessage());
}
}
}
See Below. rs.getString("tags") is subquery with more than 1 row. I want to iterate that subquery(rs.getString("tags") ---- Like rs.next().
while (rs.next()) {
emailDto emaildto = new emailDto();
emaildto.setMid(rs.getInt("id"));
emaildto.setSub(rs.getString("sub"));
emaildto.setMessage(rs.getString("message"));
while(rs.getString("tags").next()){
arrtags[i] = rs.getString(1);
}
emaildto.setTags(arrtags);
rs.getString("tags") does not work --- and contain more than 1 rows. How to extract it. Is there any technique?
Try something like this:
Array tagsArray = rs.getArray("tags");
String[] tags = (String[])tagsArray.getArray();
this is not answer. this is complete code
List emails = new ArrayList();
String listQuery = "select mid, sub, message, "
+ " (select emailid from sub_ids where sub_ids.messageid= sub_mail_list.mid ) // this query fetch more than one row.
as refid"
+ " from sub_mail_list";
PreparedStatement ps = null;
ResultSet rs;
try {
ps = DatabaseConnectionUtil.getConnection().prepareStatement(
listQuery);
rs = ps.executeQuery(listQuery);
while (rs.next()) {
emailDto emaildto = new emailDto();
emaildto.setMid(rs.getInt("mid"));
emaildto.setSub(rs.getString("sub"));
emaildto.setMessage(rs.getString("message"));
Array tagsArray = rs.getArray("refid");
List<vtbDto> vtbdtosvr = new ArrayList<vtbDto>();
int[] tags = (int[])tagsArray.getArray();
for (int i = 0; i < tags.length; i++) {
vtbDto vtbdto = new vtbDto();
vtbdto.setRefid(tags[i]);
vtbdtosvr.add(vtbdto);
}
emaildto.setAr(tagsArray);
emails.add(emaildto);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
DatabaseConnectionUtil.closeAll(ps);
}
return emails;
And this is code to print function
List emailDtos = emaildao.getAllemails();
for (emailDto emailDto2 : emailDtos) {
System.out.println( emailDto2.getMid());
System.out.println( emailDto2.getSub());
System.out.println( emailDto2.getMessage());
List<vtbDto> vtbdtos= emailDto2.getVtbdtolst();
for (vtbDto vtbdto2 : vtbdtos) {
System.out.print(vtbdto2.getRefid() + ", ");
}
}
and the console print "Subquery returns more than 1 row";
package canlitahmin;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class baglanti {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/canlitahmin";
// Database credentials
static final String USER = "root";
static final String PASS = "";
public static List<Integer> id = new ArrayList<Integer>();
public static List<Integer> evgol = new ArrayList<Integer>();
public static List<Integer> kuralid = new ArrayList<Integer>();
public static List<String> kural = new ArrayList<String>();
public static List<Integer> depgol = new ArrayList<Integer>();
public static List<Integer> dakika = new ArrayList<Integer>();
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Statement stmt2 = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
stmt2 = conn.createStatement();
String sql;
String sql2;
sql = "SELECT id, evgol, depgol, dk FROM maclar";
sql2="SELECT id,kural from kurallar";
ResultSet rs = stmt.executeQuery(sql);
ResultSet rs2 = stmt2.executeQuery(sql2);
int i=0;
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
id.add(rs.getInt("id"));
evgol.add(rs.getInt("evgol"));
depgol.add(rs.getInt("depgol"));
dakika.add(rs.getInt("dk"));
//Display values
System.out.print("ID: " + id.get(i));
System.out.print(", Evgol: " + evgol.get(i));
System.out.print(", Depgol: " + depgol.get(i));
System.out.println(", dakika: " + dakika.get(i));
i++;
}
int k=0;
while(rs2.next()){
//Retrieve by column name
kuralid.add(rs2.getInt("id"));
kural.add(rs2.getString("kural"));
//Display values
System.out.print("KURALID: " + kuralid.get(k));
System.out.println(", KURAL: " + kural.get(k));
k++;
}
for(int l=0;l<id.size();l++){
int BYTG=evgol.get(l);
int DEPTG=depgol.get(l);
/* int DK=dakika.get(l);
int MACKODLARI=id.get(l);*/
for(int j=0;j<kuralid.size();j++){
###if(kural.get(j))###{ // ERROR**********************************
double a=BYTG+DEPTG+0.5;
int b=BYTG+DEPTG;
String kural="Tahmin:"+a+" üstü ve "+b+" üstü";
System.out.println(kural);
}}
}
//STEP 6: Clean-up environment
rs.close();
rs2.close();
stmt.close();
stmt2.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
java if statement string comparison. my database datas get in "kural.get(j)"
but kural.get(j) error. because its string variable.
Question: String a=b>0 && c>0 -- if(a) how i use? String code in if with variable
This can be done programmatically with the JavaCompiler and the javax.tools package
As a related question, see How do I programmatically compile and instantiate a Java class?
The solution is the same.
You cannot easily do that with Strings. What you can do is make an interface like this
interface IntIntPredicate {
public boolean test(int i, int j);
}
Then you can do (in Java 8):
IntIntPredicate a = (i, j) -> i == 1 && j <= 2;
IntIntPredicate b = (i, j) -> i <= 0 && j == 2;
Then later you can do:
if (a.test(i, j)) {
// do something
} else if (b.test(i, j)) {
// do something else
}
This is possible in earlier versions of Java, but the syntax is more clumsy.
If it is necessary for the data to be entered as a String, it would probably not be too difficult to write a method to parse a String (treating i and j as the first and second arguments) and return an IntIntPredicate
public static IntIntPredicate parse(String x) {
// This is going to require a lot of work, but
// there are many questions on this site about how
// to parse expressions such as "(2 + 3) * 9"
}
You could make a method, like:
boolean predicate(i,j) {
if (i==1 and j <=2) {
return true;
}
return false;
}
And then invoke the method like this:
if (predicate(i,j)) {
System.out.println("a");
}
You can also used ScriptEngine, but you need to translate the logic to a scripting language like Javascript.
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
/**
*
* #author afshin
*/
public class Blah {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws ScriptException {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
int i = 1;
int j = 1;
String a = i + "==1 && " + j +"<=2";
String b= i + "<=0 && " + j+"==2";
if (((Boolean) engine.eval(a)))
System.out.println("a is true");
if (((Boolean) engine.eval(b)))
System.out.println("b is true");
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this program:
class DataRetrieve {
DataRetrieve() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/phonebook", "root", "1234");
Statement st = con.createStatement();
st.executeQuery("select * from contacts");
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public class MainProgram {
public static void main(String[] args) {
DataRetrieve dr = new DataRetrieve();
//here i want to print that table rows into Console using this
System.out.println(); // How do you print here that table rows?
}
}
Can anyone explain how to print this database information in System.out.println?
You can create a ResultSet.
ResultSet rs = st.executeQuery("select * from contacts");
Then you can iterate over ResultSet, and get the rows.
while (rs.next()) {
System.out.println(rs.getString(1)); //gets the first column's rows.
}
To get all the column's datas:
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for(int i = 1; i < columnsNumber; i++)
System.out.print(rs.getString(i) + " ");
System.out.println();
}
If you want to print the database information from MainProgram calls, you can return the ResultSet and iterate over it in your main method.
In this case you should create a method in MainProgram.
class DataRetrieve {
DataRetrieve() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/phonebook", "root", "1234");
Statement st = con.createStatement();
rs = st.executeQuery("select * from contacts");
}
catch(Exception e) {
e.printStackTrace();
}
}
public ResultSet getResultSet() {
return rs;
}
private ResultSet rs = null;
}
And in your main method:
public static void main(String[] args) {
DataRetrieve dr = new DataRetrieve();
//here i want to print that table rows into Console using this
System.out.println(); // How do you print here that table rows?
ResultSet rs = dr.getResultSet();
while (rs.next()) {
System.out.println(rs.getString(1)); //gets the first column's rows.
}
}
Use the following code:
class DataRetrieve {
DataRetrieve() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/phonebook", "root", "1234");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from contacts");
System.out.println(rs.getInt(1));
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public class MainProgram {
public static void main(String[] args) {
DataRetrieve dr = new DataRetrieve();
//here i want to print that table rows into Console using this
System.out.println(); // How do you print here that table rows ?
}
}
Well I have caught the rows returned from database in ResultSet instance. You can use getInt(xxx), getString(xxx) and etc to get the related values and then to print them.
One basic fault you did is opened the connection but never closed it. Its not a good practice you should always close it for releasing the resources.
In your code first st.executeQuery("select * from contacts"); will return a ResultSet object what you need to do is just iterate the ResultSet and get the rows.
DataRetrieve() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("yourUrl", "userName", "password");
Statement st = con.createStatement();
ResultSet resultSet = st.executeQuery("select * from contacts");
while(resultSet.next())
{
String columnName1= rs.getString("nameOfColumn1");
int columnName2= rs.getInt("nameOfColumn2");
float columnName3= rs.getFloat("nameOfColumn3");
System.out.println(columnName1+"\t"+ columnName2+"\t"+ columnName3);
}
}
}
catch(SQLException e) {
e.printStackTrace();
}
finally{
//dont forget the closing statements
}
i want to get the list generated in the following code as string before return from the function "LookUpTransaction". what should i do.?
public String[] LookUpTransaction() {
List list=new ArrayList();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bank", "root", "root");
PreparedStatement ps = con
.prepareStatement("select accountno,details,amount from transaction");
rs = ps.executeQuery();
while(rs.next()){
list.add(rs.getString(1));
list.add(rs.getString(2));
list.add(rs.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
}
String[] strarray = new String[list.size()];
return list.toArray(strarray);
}
You could use return Arrays.toString(strarray); In this case you have to change the return type of your method to String. That is your code must be modified as shown below:
public String LookUpTransaction() {
List list=new ArrayList();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bank", "root", "root");
PreparedStatement ps = con
.prepareStatement("select accountno,details,amount from transaction");
rs = ps.executeQuery();
while(rs.next()){
list.add(rs.getString(1));
list.add(rs.getString(2));
list.add(rs.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
}
String[] strarray = new String[list.size()];
strarray = list.toArray(strarray);
return Arrays.toString(strarray);
}
Please note that the Arrays.toString(strarray) returns a string representation of the contents of the specified array (strarray in your scenario). The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). If you are looking to iterate over the list & concatenating the elements you could try something like this:
public String LookUpTransaction() {
List list=new ArrayList();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bank", "root", "root");
PreparedStatement ps = con
.prepareStatement("select accountno,details,amount from transaction");
rs = ps.executeQuery();
while(rs.next()){
list.add(rs.getString(1));
list.add(rs.getString(2));
list.add(rs.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
}
StringBuilder stringBuilder = new StringBuilder();
for (String str : list) {
stringBuilder.append(str);
}
return stringBuilder.toString();
}
Use List.toArray(), followed by Arrays.toString()
String[] y = x.toArray(new String[0]);
Arrays.toString(y)