How do I work with aws rds myql on eclipse(Java)? - mysql

I have downloaded aws sdk and connected my account and the database. But now I do not know what I need to do next. How do insert, delete or create table through java on eclipse.
I know to do these in a local database. I tried changing the url in getConnection() function to the my endpoint on eclipse but I keep getting error stating
"Access denied for user 'aws'#'xxx.xxx.xxx.xxx' (using password: YES)" (real IP modified for security reasons).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class MySQLAccess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private static final String url = "jdbc:mysql://aws.cyduxshnlizb.ap-south-1.rds.amazonaws.com:3306";
final private String user = "myusername";
final private String passwd = "mypassword";
public void readDataBase() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection(url,user,passwd);
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select * from feedback.comments");
writeResultSet(resultSet);
// PreparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into feedback.comments values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from feedback.comments");
// Parameters start with 1
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "TestEmail");
preparedStatement.setString(3, "TestWebpage");
preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
preparedStatement.setString(5, "TestSummary");
preparedStatement.setString(6, "TestComment");
preparedStatement.executeUpdate();
preparedStatement = connect
.prepareStatement("SELECT myuser, webpage, datum, summary, COMMENTS from feedback.comments");
resultSet = preparedStatement.executeQuery();
writeResultSet(resultSet);
// Remove again the insert comment
preparedStatement = connect
.prepareStatement("delete from feedback.comments where myuser= ? ; ");
preparedStatement.setString(1, "Test");
preparedStatement.executeUpdate();
resultSet = statement
.executeQuery("select * from feedback.comments");
writeMetaData(resultSet);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeMetaData(ResultSet resultSet) throws SQLException {
// Now get some metadata from the database
// Result set get the result of the SQL query
System.out.println("The columns in the table are: ");
System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
for (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
System.out.println("Column " +i + " "+ resultSet.getMetaData().getColumnName(i));
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("myuser");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Website: " + website);
System.out.println("Summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
}
// You need to close the resultSet
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
}

Related

inserting two tables from multiple databases in jdbc

How to insert the two tables from two databases in jdbc is it possible?
I have the code but its not working
public class MergeData {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
public static void main(String[] args) throws SQLException {
//"jdbc:mysql://localhost:3306/fhv1", "root", "root"
DBDataFetcher database1 = new DBDataFetcher("jdbc:mysql://localhost:3306/fhv1", "root", "root");
List<Object> restDetailsList = (List<Object>) database1.fetchTableRows("restdetails");
database1.closeConnection();
long restid = 0;
for(Object obj : restDetailsList) {
if (obj instanceof RestDetails) {
restid = ((RestDetails) obj).getRest_id();
System.out.print(restid + " ");
}
}
DBDataFetcher database2 = new DBDataFetcher("jdbc:mysql://localhost:3306/test", "root", "root");
List<Object> restLocationList = (List<Object>) database2.fetchTableRows("restlocation");
database2.closeConnection();
for(Object obj : restLocationList) {
if (obj instanceof RestLocation) {
((RestLocation) obj).setRest_id(++restid);
System.out.print(((RestLocation) obj).getRest_id() + " ");
restDetailsList.add(obj);
}
}
DBDataMerger merger = new DBDataMerger("jdbc:mysql://localhost:3306/db", "root", "root");
merger.mergeTable(restDetailsList, "restdetails");
merger.closeConnection();
}
}
In plain JDBC, you should create two connections (one for each database)
public Connection getDbConnection(String dbUrl, String driver, String user, String psw){
Connection conn=null;
try{
Class.forName(driver);
conn = DriverManager.getConnection(dbUrl,user,psw);
}catch(SQLException e){
//log exception
}
return conn;
}
And to insert records you can do something like
public void insertRecord(){
//add try and catch/finally
//inserting into 1st DB
Connection conn1 = getDBConnection(dbURl1, driver1, user1, psw1);
Statement stmt = conn1.CreateStatement();
String insert1 = "insert into tbl1 (a,b,c) values(1,2,2);
stmt.executeUpdate(insert1);
//inserting into 2nd DB
Connection conn2 = getDBConnection(dbURl2, driver2, user2, psw2);
stmt = conn2.CreateStatement();//reassing statement or use a new one
String insert2 = "insert into tbl2 (a,b,c) values(1,2,2);
stmt.executeUpdate(insert2);
}
Normally, you'll want to use a PreaparedStatement instead of Statement (because it's usually faster and more secure than a Statement)

how do i use select statment

I want to use select max from a table. I want to use a PreparedStatement. I have a composite primary key which consists of the t.v series and the epo number. When I add new epo it will for table and bring the t.v series code from guidline table the content of all the programs and the code for each and then add to the new table. I want it to get the last epo by getting the max and then increment +1 "an automation app".
So how can I select max where id =??
If you get me its like
pstm2=con.prepareStatement(max);
String max="select MAX(epono) as eponoo from archieve wwhere id like ? ";
This program would be helpful
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SelectRecordsUsingPreparedStatement {
public static Connection getConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#localhost:1521:databaseName";
String username = "name";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "select deptno, deptname, deptloc from dept where deptno > ?";
pstmt = conn.prepareStatement(query); // create a statement
pstmt.setInt(1, 1001); // set input parameter
rs = pstmt.executeQuery();
// extract data from the ResultSet
while (rs.next()) {
int dbDeptNumber = rs.getInt(1);
String dbDeptName = rs.getString(2);
String dbDeptLocation = rs.getString(3);
System.out.println(dbDeptNumber + "\t" + dbDeptName + "\t" + dbDeptLocation);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Query MySQL DB using preparedStatement.setDate

public java.util.List<Tag> getAlltagsByDate(String date ){
DataSource dataSource = new DataSource();
Connection conn = dataSource.createConnection();
ResultSet resultSet = null;
PreparedStatement stmt = null;
Tag tags_Data = new Tag();
String query = "select * from tag_data where tag_data_date = ?";
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date nn =df.parse(date);
stmt = conn.prepareStatement(query);
stmt.setDate(1, java.sql.Date.valueOf(date));
resultSet = stmt.executeQuery(query);
I am getting an error
Can anyone help me with this,
I need to query mySQL db where date = input in html
No, skip the Date part; simply use the string. Let's see the value of (String date ).
MySQL is happy if you can end up with ... tag_data_date = '2015-12-11'.
If String date looks like '2015-12-11', then the conversion to Date is unnecessary.
I have presented a solution. As you have not mentioned much about your DB structure, so ,
Consider test as database name, and consisting of table tag_data having two columns id and tag_data_date as shown below.
CREATE TABLE `tag_data` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`tag_data_date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Also consider data in table as
INSERT INTO `tag_data` (`id`, `tag_data_date`) VALUES
(1, '2015-12-20 00:00:00');
And your java class as below
public class JDBCPreparedStatementExample {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver"; //mysql driver class
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/test"; //connectionstring
private static final String DB_USER = "root"; //mysql username
private static final String DB_PASSWORD = "root"; //mysql password
public static void main(String[] argv) throws ParseException {
try {
getDateForDate("2015-12-20"); //time passed as arguement
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
//Method to interact with DB and print data,this can be changed to return value of List<Key> as per your requirement
private static void getDateForDate(String date) throws SQLException, ParseException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date dateCal =df.parse(date); // parse date in String to Date Object
String updateTableSQL = "select * from tag_data where tag_data_date = ?";
try {
//get DB connection
dbConnection = getDBConnection();
// Create preapared statement
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setDate(1, new Date(dateCal.getTime()));//convert java.util.Date to java.sql.Date
// execute update SQL stetement
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getString(2);
int id = resultSet.getInt("id");
Date tag_data_date = resultSet.getDate("tag_data_date");
System.out.println("Date: " + tag_data_date);
System.out.println("Comment: " + id);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}

Importing csv file in mysql database

I have a csv file with 8 columns. When I am importing the csv file into mysql database, it is ignoring the 2nd column and shifting the rest of the data from the other columns to the left, please help.
I think the problem is with the csv file as some csv files are uploaded successfully. How can I fix it?
This is my query to store csv file into database:
LOAD DATA INFILE '$file_name' INTO TABLE import
FIELDS TERMINATED BY '|'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(#srno,#customer_name,#date,#mobno,#city,#state,#type,#telecaller)
SET customer_name=#customer_name,date=#date,mobno=#mobno,city=#city,
state=#state,type=#type,telecaller=#telecaller,datetime='$datetime'
This code worked for me. Test it out with a local database.
package Example_Import;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.io.*;
import java.lang.String;
import java.util.Scanner;
public class Example {
//import mysql-connector-java-5.1.32.jar
//http://www.tutorialspoint.com/jdbc/jdbc-create-tables.htm
private static String JDBC_URL = "jdbc:mysql://localhost:3306/sakila";
private static String USER = "root";
private static String PASSWORD = "2004";
public static void main(String[] args) throws IOException {
Connection myConnection = null;
Statement statement = null;
PreparedStatement preparedStatement = null;
try{
//CONNECTING TO THE DATABASE
myConnection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
System.out.println("Connected to database"); //CONNECTED
//CREATING TABLE IN THE DATABASE
System.out.println("Creating table in given database...");
statement = myConnection.createStatement();
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" last VARCHAR(25), " +
" first VARCHAR(25), " +
" balance FLOAT, " +
" Credit FLOAT," +
" Date DATE," +
" Rating CHAR," +
" PRIMARY KEY ( id ))";
statement.executeUpdate(sql);
System.out.println("Created table in given database...");
statement.close(); //closing statement
//CREATING A PREPARED STATEMENT
String insertTableSQL = "INSERT INTO REGISTRATION"
+ "(id, last, first, balance, Credit, Date, Rating) VALUES"
+ "(?,?,?,?, ?, ?, ?)";
preparedStatement = myConnection.prepareStatement(insertTableSQL);
//RETRIEVING INFORMATION FROM CSV FILE
//opening a file input stream
BufferedReader reader = new BufferedReader(new FileReader("SAMPLE.csv"));
String line = null; //line read from csv
Scanner scanner = null; //scanned line
SimpleDateFormat date = new SimpleDateFormat("mm/DD/yyyy");
reader.readLine(); //omits the first line
//READING FILE LINE BY LINE AND UPLOADING INFORMATION TO DATABASE
while((line = reader.readLine()) != null){
scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNext()){
preparedStatement.setInt(1,Integer.parseInt(scanner.next()));
preparedStatement.setString(2, scanner.next());
preparedStatement.setString(3, scanner.next());
preparedStatement.setFloat(4, Float.parseFloat(scanner.next()));
preparedStatement.setFloat(5, Float.parseFloat(scanner.next()));
try {
java.util.Date d;
d = date.parse(scanner.next());
preparedStatement.setDate(6, new java.sql.Date(d.getTime()));
} catch (ParseException e) {
e.printStackTrace();
}
preparedStatement.setString(7, scanner.next());
}
preparedStatement.executeUpdate();
}
preparedStatement.close();
System.out.println("Data imported");
reader.close(); //closing CSV reader
} catch (SQLException e){
e.printStackTrace();
}finally{//CLOSING CONNECTION
try{
if(statement!=null)
myConnection.close();
}catch(SQLException se){
}// do nothing
try{
if(myConnection!=null)
myConnection.close();
}catch(SQLException se){
se.printStackTrace();
}
System.out.println("Connection closed");
}
}
}

Am I Using JDBC Connection Pooling?

I am trying to determine if I am actually using JDBC connection pooling. After doing some research, the implementation almost seems too easy. Easier than a regular connection in fact so i'd like to verify.
Here is my connection class:
public class DatabaseConnection {
Connection conn = null;
public Connection getConnection() {
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setUrl("jdbc:mysql://localhost:3306/data");
bds.setUsername("USERNAME");
bds.setPassword("PASSWORD");
try{
System.out.println("Attempting Database Connection");
conn = bds.getConnection();
System.out.println("Connected Successfully");
}catch(SQLException e){
System.out.println("Caught SQL Exception: " + e);
}
return conn;
}
public void closeConnection() throws SQLException {
conn.close();
}
}
Is this true connection pooling? I am using the connection in another class as so:
//Check data against database.
DatabaseConnection dbConn = new DatabaseConnection();
Connection conn;
ResultSet rs;
PreparedStatement prepStmt;
//Query database and check username/pass against table.
try{
conn = dbConn.getConnection();
String sql = "SELECT * FROM users WHERE username=? AND password=?";
prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, user.getUsername());
prepStmt.setString(2, user.getPassword());
rs = prepStmt.executeQuery();
if(rs.next()){ //Found Match.
do{
out.println("UserName = " + rs.getObject("username") + " Password = " + rs.getObject("password"));
out.println("<br>");
} while(rs.next());
} else {
out.println("Sorry, you are not in my database."); //No Match.
}
dbConn.closeConnection(); //Close db connection.
}catch(SQLException e){
System.out.println("Caught SQL Exception: " + e);
}
Assuming that it's the BasicDataSource is from DBCP, then yes, you are using a connection pool. However, you're recreating another connection pool on every connection acquirement. You are not really pooling connections from the same pool. You need to create the connection pool only once on application's startup and get every connection from it. You should also not hold the connection as an instance variable. You should also close the connection, statement and resultset to ensure that the resources are properly closed, also in case of exceptions. Java 7's try-with-resources statement is helpful in this, it will auto-close the resources when the try block is finished.
Here's a minor rewrite:
public final class Database {
private static final BasicDataSource dataSource = new BasicDataSource();
static {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/data");
dataSource.setUsername("USERNAME");
dataSource.setPassword("PASSWORD");
}
private Database() {
//
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
(this can if necessary be refactored as an abstract factory to improve pluggability)
and
private static final String SQL_EXIST = "SELECT * FROM users WHERE username=? AND password=?";
public boolean exist(User user) throws SQLException {
boolean exist = false;
try (
Connection connection = Database.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_EXIST);
) {
statement.setString(1, user.getUsername());
statement.setString(2, user.getPassword());
try (ResultSet resultSet = preparedStatement.executeQuery()) {
exist = resultSet.next();
}
}
return exist;
}
which is to be used as follows:
try {
if (!userDAO.exist(username, password)) {
request.setAttribute("message", "Unknown login. Try again.");
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
} else {
request.getSession().setAttribute("user", username);
response.sendRedirect("userhome");
}
} catch (SQLException e) {
throw new ServletException("DB error", e);
}
In a real Java EE environement you should however delegate the creation of the DataSource to the container / application server and obtain it from JNDI. In case of Tomcat, see also for example this document: http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html
Doesn't seem like it's pooled. You should store the DataSource in DatabaseConnection instead of creating a new one with each getConnection() call. getConnection() should return datasource.getConnection().
Looks like a DBCP usage. If so, then yes. It's already pooled. And here is the default pool property value of the DBCP.
/**
* The default cap on the number of "sleeping" instances in the pool.
* #see #getMaxIdle
* #see #setMaxIdle
*/
public static final int DEFAULT_MAX_IDLE = 8;
/**
* The default minimum number of "sleeping" instances in the pool
* before before the evictor thread (if active) spawns new objects.
* #see #getMinIdle
* #see #setMinIdle
*/
public static final int DEFAULT_MIN_IDLE = 0;
/**
* The default cap on the total number of active instances from the pool.
* #see #getMaxActive
*/
public static final int DEFAULT_MAX_ACTIVE = 8;
As a follow up to BalusC's solution, below is an implementation that I can be used within an application that requires more than one connection, or in a common library that would not know the connection properties in advance...
import org.apache.commons.dbcp.BasicDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;
public final class Database {
private static final ConcurrentHashMap<String, BasicDataSource> dataSources = new ConcurrentHashMap();
private Database() {
//
}
public static Connection getConnection(String connectionString, String username, String password) throws SQLException {
BasicDataSource dataSource;
if (dataSources.containsKey(connectionString)) {
dataSource = dataSources.get(connectionString);
} else {
dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(connectionString);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSources.put(connectionString, dataSource);
}
return dataSource.getConnection();
}
}