Sql query in DAO class regarding - java

I converted date datatype to string and stored in table as a string.I want to write a query to show results between certain date.I wrote like this
public Statement getstatement(Statement s) throws SQLException {
long accid=0;
Statement s1=null;
Connection conn=DatabaseUtil.getConnection();
PreparedStatement psmt=conn.prepareStatement("select * from Account_groupc_tja05 where Account_id =?");
psmt.setLong(1,s.getAccid());
System.out.println("inside dao");
ResultSet rs=psmt.executeQuery();
while(rs.next()){
accid=rs.getLong(1);
System.out.println("inside while");
}
if(s.getAccid()==accid){
System.out.println("inside if");
PreparedStatement psmt1=conn.prepareStatement("select * from deposit1_groupc_tja05 where Account_id =? and Transaction_Date between ? and ?");
psmt1.setLong(1, accid);
psmt1.setString(2, s.getDatefrom());
psmt1.setString(3, s.getDateto());
System.out.println(s.getDateto());
ResultSet rs1=psmt1.executeQuery();
while(rs1.next()){
System.out.println("inside inner while");
s1=new Statement(rs.getString(6),rs.getLong(7),rs.getLong(4),rs.getLong(3),rs.getString(5));
System.out.println(s1);
}
}
return s1;
}
But this query is not executing. Why?

Your syntax is wrong, there is nothing like Prepared statement and you'd want to execute the ps to "execute the query". e.g.
PreparedStatement ps=con.prepareStatement("Select * from deposit where transaction_date between ? And ?");
ps.setString(1,fromdate);
ps.setString(2,todate);
ps.execute();
ps.close();
Also you need to enter your database credentials in your connection statement
Connection conn=DatabaseUtil.getConnection();
to
Connection conn=DatabaseUtil.getConnection(<databaseurl>, <username>, <password>);

Related

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

Can have two database connection in one function?

When I debug, I get this error :
Column 'place1' not found.
I was able to verify that it has column place1 in sql.
Is it because I can not have two database connection in one function? I am unsure on how to further debug the problem.
Case.java
System.out.println("The highest value is "+highest+"");
System.out.println("It is found at index "+highestIndex+""); // until now it works fine
String sql ="Select Day from menu where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
int kb=rs.getInt("Day");
System.out.println(kb);
if(kb==k) // k is a value getting from comboBox
{
String sql1 ="Select * from placeseen where ID =?";
DatabaseConnection db1 = new DatabaseConnection();
Connection conn1 =db1.getConnection();
PreparedStatement ps1 = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs1 = ps.executeQuery();
if (rs1.next())
{
String aaa=rs1.getString("place1");
String bbb=rs1.getString("place2");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
DispDay dc=new DispDay();
}
ps1.close();
rs1.close();
conn1.close();
}
else
{
System.out.print("N");
System.out.println("Sorry!!!");
}
}
ps.close();
rs.close();
conn.close();
Trace your code to see where you're getting the data. The error is on this line:
String aaa=rs1.getString("place1");
Where does rs1 come from?:
ResultSet rs1 = ps.executeQuery();
Where does ps come from?:
PreparedStatement ps = conn.prepareStatement(sql);
Where does sql come from?:
String sql ="Select Day from menu where ID =?";
There's no column being selected called place1. This query is only selecting a single column called Day.
Maybe you meant to get the result from the second prepared statement?:
ResultSet rs1 = ps1.executeQuery();
There are probably more such errors. Perhaps several (or many) more. Because...
Hint: Using meaningful variable names will make your code a lot easier to follow. ps, ps1, rs1, etc. are very easy to confuse. Name variables by the things they conceptually represent and your code starts to read like a story which can be followed. Variable names like daysQuery and daysResults and placesResults make it more obvious that something is wrong when you try to find a "place" in a variable which represents "days".
In your second query:
PreparedStatement ps1 = conn.prepareStatement(sql);
you are accidentally using the variable sql instead of your previously defined sql1. Replace it and it will be ok.

Update sql statement in servlet not in servlet

I am trying to allow the user to change the password if he enters the right username. The username is drawn from the database and compared to the username the user enter in a form. My problem is after the validation is done the UPDATE statement is not producing any result. Can someone help me out please?
String un = request.getParameter("username");
String psw = request.getParameter("password");
String cPsw = request.getParameter("cpassword");
Connection con = ConnectionHelper.getConnection();
try {
ResultSet rs = userList(con);
if (rs.next()) {
String n = rs.getString("username");
if (n.equals(un)) {
out.print("Password match");
String updateQuery = "UPDATE RegisteredUserInfo SET password ='"
+ cPsw + "'WHERE username ='" + un + "'";
PreparedStatement ps1 = con.prepareStatement(updateQuery);
ps1.executeQuery();
ServletContext context = getServletContext();
RequestDispatcher rd = context
.getRequestDispatcher("/Welcome.jsp");
rd.forward(request, response);
}
}
} catch (SQLException sx) {
out.println();
}
}
public ResultSet userList(Connection con) throws SQLException {
PreparedStatement ps;
ResultSet rs;
String matchingUname = "SELECT username FROM RegisteredUserInfo";
ps = con.prepareStatement(matchingUname);
rs = ps.executeQuery();
return rs;`
Try with ps1.execute(); or ps1.executeUpdate() instead of ps1.executeQuery();
Call con.commit(); to commit the changes and Don't forget to close the resources in the end.
Check the return type of below methods to make sure that data is inserted properly.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
Ream more about Difference between execute, executeQuery, executeUpdate
Points to Remember
Use PreparedStatement instead of using single quoted query string that may cause issue. Find a sample on Using Prepared Statements
Don't forget to close the resources such as connection, result set and statement.
Use finally block to handle it or Read more about Java7 -The try-with-resources Statement
Don't simply eat the exception in catch block. Do proper handling of the exception. You can try with e.printStackTrace() while development.
You need to call executeUpdate() for SQL UPDATE (or INSERT/DELETE).
String updateQuery = "UPDATE RegisteredUserInfo SET password = ?"
+ " WHERE username = ?";
PreparedStatement ps1 = con.prepareStatement(updateQuery);
ps1.setString(1, cPsw);
ps1.setString(2, un);
ps1.executeUpdate();
Also use the PreparedStatement as above. Look for SQL Injection, also escapes '.

Inserting email in SQLite database using JDBC

I am trying to insert an email ID to a table in my SQLite3 Database. In my case it successfully creates the table but gives an error while inserting a record in it - "near "#gmail": syntax error". How can i resolve this ? Here is the code -
public void insertData(String emailId, double gtse, long receivedDate) throws ClassNotFoundException, SQLException{
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:testdb.sqlite");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
ResultSet result = statement.executeQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='T1'");
if(!result.next()){
statement.executeUpdate("create table T1 (email TEXT, gtse REAL, receiveddate DATE)");
statement.executeUpdate("insert into T1 values(" + emailId + ", "+ gtse +", "+ receivedDate +")");
}
else{
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
Your core error is that for the insert query you are not enclosing the values to be inserted, in quotes. Your query, after construction, looks something like this:
insert into T1 values(whatever#gmail.com, emailtexthere, 04-07-2013)
When it should be something like this:
insert into T1 values('whatever#gmail.com', 'emailtexthere', '04-07-2013')
The SQL parser chokes while trying to parse your current query, because the syntax is incorrect. The solution to this problem is not simply to enclose the values in quotes though, but rather to use prepared statements. This is because the way you are constructing your query right now is vulnerable to SQL injection attacks. Here is an example of using a prepared statement:
PreparedStatement pStmt = conn.prepareStatement(
"INSERT INTO T1 VALUES(?, ?, ?)");
pStmt.setString(1, emailId);
pStmt.setString(2, gtse);
pStmt.setDate(3, receivedDate);
pStmt.execute();

Passing parameters to a JDBC PreparedStatement

I'm trying to make my validation class for my program. I already establish the connection to the MySQL database and I already inserted rows into the table. The table consists of firstName, lastName and userID fields. Now I want to select a specific row on the database through my parameter of my constructor.
import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.Connection;
public class Validation {
private PreparedStatement statement;
private Connection con;
private String x, y;
public Validation(String userID) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "");
statement = con.prepareStatement(
"SELECT * from employee WHERE userID = " + "''" + userID);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
x = rs.getString(1);
System.out.print(x);
System.out.print(" ");
y = rs.getString(2);
System.out.println(y);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
But it doesn't seem work.
You should use the setString() method to set the userID. This both ensures that the statement is formatted properly, and prevents SQL injection:
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
There is a nice tutorial on how to use PreparedStatements properly in the Java Tutorials.
If you are using prepared statement, you should use it like this:
"SELECT * from employee WHERE userID = ?"
Then use:
statement.setString(1, userID);
? will be replaced in your query with the user ID passed into setString method.
Take a look here how to use PreparedStatement.
There is a problem in your query..
statement =con.prepareStatement("SELECT * from employee WHERE userID = "+"''"+userID);
ResultSet rs = statement.executeQuery();
You are using Prepare Statement.. So you need to set your parameter using statement.setInt() or statement.setString() depending upon what is the type of your userId
Replace it with: -
statement =con.prepareStatement("SELECT * from employee WHERE userID = :userId");
statement.setString(userId, userID);
ResultSet rs = statement.executeQuery();
Or, you can use ? in place of named value - :userId..
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
Do something like this, which also prevents SQL injection attacks
statement = con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
You can use '?' to set custom parameters in string using PreparedStatments.
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
If you directly pass userID in query as you are doing then it may get attacked by SQL INJECTION Attack.

Categories