Query MySQL DB using preparedStatement.setDate - mysql

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;
}
}

Related

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

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) {
}
}
}

MySql.Data.MySqlClient.MySqlException : Incorrect datetime value

Hai I have to add details from one table to another which should be within to dates. These dates are read from text boxes.
But i'm getting Error:
"An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: Incorrect datetime value: '11/25/2015 12:00:00 AM' for column 'debissuedate' at row 1"
The first table is t_bondridapp with fields : id,cancode,canname,debissuedate...etc
And I have to copy from this table to new one named as bondlocal with fields :
bondid,cancode,canname,bonddate.
I've used the code
public class DBConnection
{
private DBConnection()
{
}
private string dbname = string.Empty;
public string DBName
{
get { return dbname;}
set { dbname = value;}
}
public string Password { get; set; }
private MySqlConnection mycon = null;
public MySqlConnection Connection
{
get { return mycon; }
}
private static DBConnection _instance = null;
public static DBConnection Instance()
{
if(_instance==null)
_instance=new DBConnection();
return _instance;
}
public bool IsConnect()
{
bool result = true;
if(mycon==null)
{
if (String.IsNullOrEmpty(dbname))
result = false;
string constr = string.Format("server=localhost;user id=root;password=mysql;database=pnys;",dbname);
mycon = new MySqlConnection(constr);
mycon.Open();
result = true;
}
return result;
}
public void Close()
{
mycon.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
MySqlDateTime fdate =new MySqlDateTime(DateTime.Parse(TextBox3.Text));
MySqlDateTime sdate = new MySqlDateTime(DateTime.Parse(TextBox4.Text));
var dbCon = DBConnection.Instance();
dbCon.DBName = "pnys";
if (dbCon.IsConnect())
{
string query = "INSERT INTO bondlocal (cancode,canname,bonddate) SELECT t_bondridapp.cancode,t_bondridapp.canname,t_bondridapp.debissuedate FROM t_bondridapp WHERE debissuedate>='" + fdate + "'AND debissuedate<='" + sdate + "'";
MySqlCommand cmd = new MySqlCommand(query, dbCon.Connection);
cmd.ExecuteNonQuery();
}
Server.Transfer("ReportBonds.aspx");
}
Pls Help Me...
Basically, the problem is how you're passing parameters into the database. You shouldn't need to create a MySqlDateTime yourself - just use parameterized SQL and it should be fine:
// TODO: Use a date/time control instead of parsing text to start with
DateTime fdate = DateTime.Parse(TextBox3.Text);
DateTime sdate = DateTime.Parse(TextBox4.Text);
string query = #"INSERT INTO bondlocal (cancode,canname,bonddate)
SELECT t_bondridapp.cancode,t_bondridapp.canname,t_bondridapp.debissuedate
FROM t_bondridapp
WHERE debissuedate >= #fdate AND debissuedate <= #sdate";
using (var command = new MySqlCommand(query, dbCon))
{
command.Parameters.Add("#fdate", MySqlDbType.Datetime).Value = fdate;
command.Parameters.Add("#sdate", MySqlDbType.Datetime).Value = sdate;
command.ExecuteNonQuery();
}
Basically, you should never specific values within SQL by just using string concatenation. Parameterized SQL prevents SQL injection attacks and conversion issues, and improves code readability.
(As an aside, I would urge you to ditch your current connection sharing, and instead always create and open a new MySqlDbConnection and dispose of it at the end of your operation - rely on the connection pool to make it efficient.)

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();
}
}
}
}

SEVERE: java.sql.SQLException: Column count doesn't match value count at row 1

I have Mysql datatbase, and working on servlet:
this is my Table schema:
CREATE TABLE Files (
File_Name VARCHAR(50),
File_Data Blob ,
File_Date VARCHAR(20),
File_Course_Code VARCHAR(45) REFERENCES Course(Course_Code) ,
PRIMARY KEY (File_Name , File_Date, File_Course_Code)
);
And here is the servlet code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
ServletOutputStream os = response.getOutputStream();
try {
InputStream uploadedFile = null;
DiskFileUpload fu = new DiskFileUpload();
// If file size exceeds, a FileUploadException will be thrown
fu.setSizeMax(10000000);
List fileItems = fu.parseRequest(request);
Iterator itr = fileItems.iterator();
while (itr.hasNext()) {
FileItem fi = (FileItem) itr.next();
//Check if not form field so as to only handle the file inputs
//else condition handles the submit button input
if (!fi.isFormField()) { // If the form fiel is a file
uploadedFile = fi.getInputStream();
}
}
// to get the file name:
String fileName= "String";
// to extract the date:
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String strDateNew = sdf.format(now);
HttpSession session = request.getSession();
String a = (String) session.getAttribute("fileccode");
// set connection up:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/VC", "root", "");
PreparedStatement stmt = null;
stmt = conn.prepareStatement("INSERT INTO Files (File_Name,File_Data,File_Date,File_Course_Code) VALUES (?,? ?,?)");
stmt.setString(1,fileName);
stmt.setBinaryStream(2,uploadedFile);
stmt.setString(3,strDateNew);
stmt.setString(4,a);
stmt.executeUpdate();
} catch (FileUploadException e) {
os.print(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
os.close();
}
}
I have seen many posts about this error, but almost all of them were having Syntax error in writing the query.
I have no syntax error i believe.
but maybe (File_Data) as a primary key and default null makes something wrong?
Your missing a comma
VALUES (?,? ?,?)
should be
VALUES (?,?,?,?)