java loop store database and call it back error - java

When created random email and store in mysql database its working fine then i try to print that random email but i can't. Anyone help me where can i edit my code?
Without ResultSet rs=statement.executeQuery("select * from user_data"); and
System.out.println(rs.getString(1)); its working fine
note:- someone please edit my grammar
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Random;
public class new_test {
public static void main(String[] args) {
ArrayList<String>objectsToStores = new ArrayList<>();
Random rad = new Random();
for (int j=1; j<=3; j++ )
{
objectsToStores.add("usename"+rad.nextInt()+"#gmail.com");
}
try {
Class.forName("com.mysql.jdbc.Driver") ;
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "");
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
ResultSet rs=statement.executeQuery("select * from user_data");
for (String x : objectsToStores ) {
statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" +x +"')");
}
while(rs.next())
System.out.println(rs.getString(1));
connection.commit();
statement.close();
connection.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

The problem was the order that you were using for executing queries on the db
I just moved down the line
ResultSet rs = statement.executeQuery("select * from user_data");
after
statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" + x + "')");
This solve the problem because when you execute the UPDATE (second query) the ResultSet from the SELECT
get closed by the statement so you can't iterate it, and give you an error
try {
// This is not needed anymore with the new driver
//Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "");
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
for (String x : objectsToStores) {
statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" + x + "')");
}
// I just moved this line down
ResultSet rs = statement.executeQuery("select * from user_data");
while (rs.next())
System.out.println(rs.getString(1));
connection.commit();
statement.close();
connection.close();
} catch (Exception e) {
throw new RuntimeException(e);
}

Related

Trying to write java code that uses a switch to select data from sqlite database

I am trying to query data from the database using JDBC, but I cant get the SELECT SUM() to work on the third switch case. All the other cases and SELECT amount on the third case work just fine, but when I try to use SELECT SUM(amount) it gives the error "no such column: 'amount'".
Here is my code:
package net.sqlitetutorial;
import java.util.Scanner;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLMain {
private Connection connect() {
String url = "jdbc:sqlite:C://sqlite/db/test.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
public void selectAll(){
String sql = "SELECT name, amount FROM names ORDER BY amount desc";
try (Connection conn = this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)){
while (rs.next()) {
System.out.println(rs.getString("name") + "\t" +
rs.getInt("amount"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void selectNames(){
String sql = "SELECT name FROM names ORDER BY name";
try (Connection conn = this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)){
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void selectAmount(){
String sql = "SELECT sum(amount) FROM names";
try (Connection conn = this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)){
while (rs.next()) {
System.out.println(rs.getInt("amount"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
SQLMain app = new SQLMain();
int number;
Scanner console = new Scanner(System.in);
System.out.println("Choose one by entering a number:\n 1. List all ordered by most popular name first\n 2. List names in alphabetical order");
number = console.nextInt();
switch (number)
{
case 1 :
app.selectAll();
break;
case 2 :
app.selectNames();
break;
case 3 :
app.selectAmount();
break;
default:
System.out.println("Invalid input");
}
}
}
This is the error it gives out:
no such column: 'amount'
In this statement:
SELECT sum(amount) FROM names
there is no column returned by the name amount.
You must set an alias to the column returned:
SELECT sum(amount) AS amount FROM names
Or, without aliasing the column, you could get its value by its index which is 1:
System.out.println(rs.getInt(1));
This is because the result contains SUM(amount) and not the column amount.
You can for instance fix this by changing the query to
"SELECT sum(amount) AS amount FROM names"
or getting the result by index
rs.getInt(1);
Your query really doesn't have a an amount column in it - it has sum(amount). You could use an alias as forpas' answer suggests, or just the index (remember - column indexes in JDBC are one-based):
while (rs.next()) {
System.out.println(rs.getInt(1));
}

how to insert bulk data from one database to another data base same structure using java

I have two SQL server running on two different location having same structure but different IP a = 100.0.0.1 and IP b = 192.0.0.1. I have a table a.table and b.table of same structure. Now i want to move all data that is in a. Table from 100.0.0.1 machine to b.table machine 192.0.0.1 .I want to transfer this data using java either connection or by hibernate. Currently i am doing this manually by running SQL query.
Here is the code you can use
import java.sql.*;
import java.io.*;
import java.util.*;
public class test1
{
public static void main(String[] argv) throws Exception
{
try
{
Connection con = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/old","user","pass");
Connection con1 = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/new","user","pass");
String sql = "INSERT INTO users("+ "name,"+ "active,"+ "login,"+ "password)"+ "VALUES(?,?,?,?)";
Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
PreparedStatement pstmt = con1.prepareStatement(sql);
ResultSet rs = statement.executeQuery("SELECT * FROM users");
while ( rs.next() )
{
String nm = rs.getString(2);
Boolean ac = rs.getBoolean(3);
String log = rs.getString(4);
String pass = rs.getString(5);
pstmt.setString(1, nm);
pstmt.setBoolean(2, ac);
pstmt.setString(3, log);
pstmt.setString(4, pass);
pstmt.executeUpdate();
}
con.close();
con1.close();
}
catch (SQLException e)
{
System.out.println("could not get JDBC connection: " +e);
}
}
}
Create a connection with something like this
Connection con=DriverManager.getConnection(url, dbProperties);
//then create a query
String query = "select * from a.table";
Statement statement = connect.createStatement(query);
save result in resultset or somewhere else : ResultSet rs = statement.executeQuery(); then create a second connection to your other database like above and call an insert for each result in your resultset. there might be much better methods to insert so much data. i hear about bulk operations but i don't know how they work

Fill textboxes with null values

I'm writing a Webapp where there is data that has to be pulled from database and displayed in textboxes. Everything is working fine. But I need to display the value as No Data Available in those textboxes if(!rs.next()), currently I'm trying the below code.
package org.DAO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.bean.UserBean;
import org.code.general.DBConnection;
import org.code.general.GetTheUserDetails;
public class GetDataDAO {
DBConnection dbConnection = new DBConnection();
GetTheUserDetails getTheUserDetails = new GetTheUserDetails();
public List<UserBean> list(String systemUserName) throws Exception {
List<UserBean> userBeans = new ArrayList<UserBean>();
try {
Connection conn = dbConnection.getConn();
Statement stmt = dbConnection.getStmt();
ResultSet rs = dbConnection.getRs();
String excelPath = dbConnection.getExcelPath();
String queryString = null;
dbConnection.createClassForNameForExcel();
conn = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=" + excelPath + "; READONLY=FALSE;");
System.out.println("Connecting to database…");
System.out.println("Oracle JDBC Driver Registered!");
if (conn != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
stmt = conn.createStatement();
queryString = "Select * from [" + dbConnection.getSheetPath()
+ "$] where STATE IS NULL and [Case Owner] = '"
+ getTheUserDetails.getUserNameDetails(systemUserName) + "'";
System.out.println("Query is " + queryString);
rs = stmt.executeQuery(queryString);
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("bno of cols are " + rsmd.getColumnCount());
while (rs.next()) {
if (rs.next()) {
UserBean userBean = new UserBean();
userBean.setCaseNumber(rs.getString(1));
userBean.setCaseOwner(rs.getString(2));
userBean.setStatus(rs.getString(4));
userBean.setIssue(rs.getString(5));
userBean.setReason(rs.getString(6));
userBean.setDateOpened(rs.getString(7));
userBean.setAge(rs.getInt(8));
userBeans.add(userBean);
} else {
UserBean userBean = new UserBean();
userBean.setCaseNumber("None");
userBean.setCaseOwner("None");
userBean.setStatus("None");
userBean.setIssue("None");
userBean.setReason("None");
userBean.setDateOpened("None");
userBean.setAge(Integer.parseInt("None"));
userBeans.add(userBean);
}
}
rs.close();
conn.commit();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return userBeans;
}
}
As per my understanding, I've written trying the below algorithm,
if(rs.next)
then create the bean and add the values from database,
else
create the bean and add the values as None
please let me know where am I going wrong and how can I fix this.
Thanks
if(rs.next)
then create the bean and add the values from database,
else
set the bean as null
In jsp check if bean is null then No Data Available under text boxes. Ideally you should do it in servlet or controller as jsp should be as light as it can be
public boolean next()
Moves the cursor to the next row. This method returns false if there are no more rows in the result set.
So when you call rs.next() twice, once in while and once in if , you will miss one row every time.
Try remove if condition
The code is skipping a row per iteration:
while (rs.next()) {
if (rs.next())
If the result set is either 0 or 1 row then just use rs.next():
if (rs.next())
{
// Use 'rs'.
}
else
{
// "None".
}
Additionally:
the null check on conn is superfluous as DriverManager.getConnection() throws an exception if it fails.
use try-with-resources to ensure Connection, Statement and ResultSet are always released.
You would have to have logic like this, if the rows are empty:
rs = stmt.executeQuery(queryString);
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("bno of cols are " + rsmd.getColumnCount());
while (rs.next()) {
UserBean userBean = new UserBean();
userBean.setCaseNumber(rs.getString(1));
userBean.setCaseOwner(rs.getString(2));
userBean.setStatus(rs.getString(4));
userBean.setIssue(rs.getString(5));
userBean.setReason(rs.getString(6));
userBean.setDateOpened(rs.getString(7));
userBean.setAge(rs.getInt(8));
userBeans.add(userBean);
}
if(userBeans.size() == 0) {
UserBean userBean = new UserBean();
userBean.setCaseNumber("None");
userBean.setCaseOwner("None");
userBean.setStatus("None");
userBean.setIssue("None");
userBean.setReason("None");
userBean.setDateOpened("None");
userBean.setAge(Integer.parseInt("None"));
userBeans.add(userBean);
}
rs.close();
conn.commit();
conn.close();
But if the rows are not empty, just containing null values, then you can have the logic like this:
rs = stmt.executeQuery(queryString);
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("bno of cols are " + rsmd.getColumnCount());
while (rs.next()) {
UserBean userBean = new UserBean();
String value = rs.getString(1) == null ? "None" : rs.getString(1);
// you do this for all the columns, from 1 to 8
userBean.setCaseNumber(rs.getString(1));
userBean.setCaseOwner(rs.getString(2));
userBean.setStatus(rs.getString(4));
userBean.setIssue(rs.getString(5));
userBean.setReason(rs.getString(6));
userBean.setDateOpened(rs.getString(7));
userBean.setAge(rs.getInt(8));
userBeans.add(userBean);
}
rs.close();
conn.commit();
conn.close();

class to connect java program to database(which accepts parameters)

I'm trying to write a class that will accept two strings and an int (username and password and score) from a quizgame, which eventually will come from a GUI, at the minute I'm just passing them through from the main, and pass them into a database to be inserted.
I have the JConnector jar file added and am working in Eclipse.
Here is my code
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
//public
class DbConnect {
private java.sql.Connection con;
private java.sql.Statement st;
private ResultSet rs;
public DbConnect() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3307/nostalgic", "root", "usbw");
st = con.createStatement();
} catch (Exception ex) {
System.out.println("Error is " + ex);
}
}
public void setData(String n, String p, int x) {
try {
String query = "select * from nostalgic";
String query1 = "INSERT INTO nostalgic values (n,p,x)";
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.executeUpdate();
rs = st.executeQuery(query);
System.out.println("records from database");
while (rs.next()) {
String name1 = rs.getString("name");
String pw = rs.getString("password");
int score = rs.getInt("score");
System.out.println("Name : " + name1);
System.out.println("Password : " + pw);
System.out.println("Score : " + score);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
The error I get is
Unknown column 'n' in 'field list'
I can directly put a string in like 'john' but that is no use to me in this situation.
Instead of INSERT INTO nostalgic values (n,p,x) you should have
INSERT INTO nostalgic values (?,?,?) and then:
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.setString(1,n);
statement3.setString(2,p);
statement3.setString(3,x);
statement3.executeUpdate();
in
String query1 = "INSERT INTO nostalgic values (n,p,x)";
n,p,x are not being replaced with the values, they are just being considered as some char that's why you get this error
Edit : before statement3.executeUpdate();
String query1 = "INSERT INTO nostalgic values (?,?,?)";
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.setString(1,n);
statement3.setString(2,p);
statement3.setInt(3,x);
Update: you may wonder why Unknown column 'n' in 'field list'?
Because as insert query in sql can have this structure
INSERT INTO table (col1,col2,...) values (`val1`,`val2`,....)
but then values need to be inside `` if hard coded so if there is no `` sign they are considered as column name.
Mick,
the problem is that you don't pass actual parameters to your query when doing statement3.executeUpdate();. Check this link to see how to do it: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html.
You cannot do it like that try this:
Class.forName("com.mysql.jdbc.Driver");
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/nostalgic","root","usbw") {
PreparedStatement pr = null;
String query = "INSERT INTO nostalgic VALUES ((?), (?), (?))";
pr = con.prepareStatement(query);
pr.setString(1, n);
pr.setString(2, p);
pr.setString(3, x);
int status = pr.executeUpdate();
}catch (ClassNotFoundException | SQLException e) {
System.out.println(e.getMessage());
}
There are some mistakes in your code...
Correct imports
Insert statement
Your code will be like that:
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.jdbc.Statement;
// you imported sql innecessary statements...
//public
class DbConnect {
// dont need complete path, you already imported it
private Connection con;
private Statement st;
private ResultSet rs;
public DbConnect() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3307/nostalgic", "root", "usbw");
st = con.createStatement();
} catch (Exception ex) {
System.out.println("Error is " + ex);
}
}
public void setData(String n, String p, int x) {
try {
String query = "select * from nostalgic";
String query1 = "INSERT INTO nostalgic values (?,?,?)";
// no need to define vars here,
// just number of places to be inserted here ----^
PreparedStatement statement = con.prepareStatement(query1);
// prepare statement
statement = con.prepareStatement(query);
// insert the variables in places you prepared before
// and matching the types you need!!!
statement.setString(1,n);
statement.setString(2,p);
statement.setInt(3,x);
rs = st.executeQuery(query);
System.out.println("records from database");
while (rs.next()) {
String name1 = rs.getString("name");
String pw = rs.getString("password");
int score = rs.getInt("score");
System.out.println("Name : " + name1);
System.out.println("Password : " + pw);
System.out.println("Score : " + score);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}

ERROR: java.sql.SQLException: [Microsoft][ODBC dBASE Driver] Too few parameters. Expected 1

I am using MS Access 2007 and trying to insert the data and I am getting the exception and I have tried it by using [] braces but it is not working.It create the DBF file successfully but not generating the exact Output.
import java.sql.*;
public class Test
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dataSourceName = "mdbTEST";
String dbURL = "jdbc:odbc:" + dataSourceName;
Connection con = DriverManager.getConnection(dbURL, "","");
// creating a java.sql.Statement so I can run queries
Statement s = con.createStatement();
s.execute("create table TESTME ( olumn_name integer )");
// creating a table
// inserting some data into the table
s.execute("insert into TESTME values(3)");
// selecting the data from the table
s.execute("[select column_name from TESTME]");
//getting any ResultSet that came from our query
ResultSet rs = s.getResultSet();
if (rs != null)
// if rs == null, then there is no ResultSet to view
while ( rs.next() )
{
/* the next line will get the first column in our current row's ResultSet
as a String ( getString( columnNumber) ) and output it to the screen */
System.out.println("[Data from column_name:]" + rs.getString(1) );
}
s.execute("drop table TESTME");
s.close();
con.close();
}
catch (Exception err)
{
System.out.println("ERROR: " + err);
}
}
}
Your statement
s.execute("[select column_name from TESTME]");
won't work because Access SQL uses square brackets to delimit table and column names, so your SQL "query" consists of a single name with no SELECT keyword. I'd suggest...
s.execute("SELECT [column_name] FROM [TESTME]");
...but that probably won't work because of a typo in your CREATE TABLE statement. Try this:
s.execute("SELECT [olumn_name] FROM [TESTME]");
Edit
The following code works for me:
import java.sql.*;
public class JDBCQuery {
public static void main( String args[] )
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\Public\\Database1.accdb;");
Statement s = conn.createStatement();
s.execute("CREATE TABLE [TESTME] ([column_name] integer)");
s.execute("INSERT INTO [TESTME] VALUES (3)");
s.execute("SELECT [column_name] FROM [TESTME]");
ResultSet rs = s.getResultSet();
if (rs!=null)
{
while (rs.next())
{
System.out.println("Data from column_name: " + rs.getString(1));
}
}
s.execute("DROP TABLE [TESTME]");
s.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
(Note that the database file Database1.accdb already existed when I ran this code.)

Categories