MySQL Jdbc convert string to date - mysql

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// date here is a string of format yyyy-MM-dd
java.util.Date date_1 = df.parse(date) ;
java.sql.Date sqldate = new java.sql.Date(date_1.getTime());
sql = "select * from fgs_stock_report where Report_date = ? ";
PreparedStatement two = con.prepareStatement(sql);
two.setDate(1,sqldate);ResultSet rs ;
rs = two.executeQuery(sql) ;
Here I get a Java Sql Exception asking for the right syntax near? . I am a beginner and I searched a lot for a solution but couldnt find. Please help me.

I think I see the problem, you are using a Statement.executeQuery(String) but you want PreparedStatement.executeQuery() - that is.
PreparedStatement two = con.prepareStatement(sql); // <-- Prepare a Statement.
two.setDate(1,sqldate); // <-- bind the parameter.
ResultSet rs ;
rs = two.executeQuery(sql) ; // <-- throw it away and use raw sql
What you want is,
ResultSet rs = two.executeQuery(); // <-- I'd use one line

Related

Request.form returns value with comma

When I run this code:
string MySQL = "Select * From RegisterDatabase Where uName = '" + Request.Form["username"] +"'";
It didn't work for me, so I tried to see what the problem was and it turns out there's a comma in MySQL.
Select * From RegisterDatabase Where uName = 'Test,'
How do I fix this?
Your code is prone to SQL Injection attack.
You want to parameterized query like this -
string query = "Select * From RegisterDatabase Where uName = #username";
// Remove "," from username
string username = Request.Form["username"].ToString().Replace(",", "");
MySqlCommand command = new MySqlCommand(query);
command.Parameters.AddWithValue("#username", username);
Or some use ?username instead of #username.
Use following
Request.Form["username"].ToString().Replace(',',' ').Trim();

JDBC pass parameters to sql query

I have
employee(id, name, company, salary);
Need to display data for given id
public static void Connect(String conString, String username, String password, int id) throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection(conString, username, password);
String query = "select * from employee where id = " + id + "" ;
ResultSet rs = null;
Statement stmt = null;
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()){
String name = rs.getString("name");
String company = rs.getString("company");
int salary = rs.getInt("salary");
System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But here we are passing the id directly. How can we pass it like parametrized queries (like how we pass ? during PreparedStatement)
in that case your query should be
String query = "select * from employee where id = ?";
instead of Statement you need to create PreparedStatement
PreparedStatement preparedStatement = conn.prepareStatement(query);
and then set your id to the prepared statement
preparedStatment.setInt(1, id);
finally execute the query
resultSet = preparedStatement.executeQuery();
It's old post but I would still like to add my answer.
I don't have enough reputation to comment on #prasad's answer, so I am adding small correction as separate answer. Actually, passing query inside praparedStatement.executeQuery() throws MySQLSyntaxErrorException because still it calls Statement.executeQuery instead of PreparedStatement.executeQuery(). And how do I know? I had to spent ample amount of time in figuring out this issue.
So use PreparedStatement.executeQuery() instead of PreparedStament.executeQuery(query).

timestamp issue in mysql

While executing the following query in querybrowser i;m getting correct date.But in jdbc code resultset is returning incorrect date.
pstmt = con.prepareStatement("select DATE(sih.loaded_date) from tab_ats_sellthroughloader_history sih order by loaded_date desc limit 1");
rs = pstmt.executeQuery();
java.sql.Timestamp saveDate = null;
while (rs.next()) {
saveDate = rs.getTimestamp(1);
}
System.out.println("result:::::::::::::::::"+saveDate);

Servlets/JSP - Unable to access database on SOAP webservice

I am trying to create a simple little webservice on a glassfish server backed by a mysql server on my netbeans
Its designed to be a very simple currency conversion service
Here is what its supposed to do
It takes an amount of money (Always in GBp) as an INT and a currency to convert it in as a string.
The service then looks up that currency from my database table to get the conversion rate with a query like
select * from exchange.rates where currency = string
Then it performs the simple calculation to convert the money into the currency and returns the amount
The problem is that i have no clue how to call that conversion rate from my mysql server, i tried and tried but nothing happens
i just keep getting the same amount i entered in.
I tried entering euro and 10
I set the rate for that in my database but i just got 10 back out when i tested the webservice
/**
* Web service operation
*/
#WebMethod(operationName = "convert")
public int convert(#WebParam(name = "currency") String currency, #WebParam(name = "amount") int amount) {
int newamount = 0;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/exhange",
"root", "25587");
PreparedStatement st =
con.prepareStatement("select * from rates where currency = '" + currency+"'");
ResultSet rs = null;
rs = st.executeQuery();
rs.first();
newamount =rs.getInt("conversion") * amount;
return newamount;
} catch (Exception e) {
System.out.println("error");
}
return amount;
}
Whe you use prepared statemen you need to pass the parameter explicitly:
PreparedStatement st = con.prepareStatement("select * from rates where currency = ?");
st.setString(1,currency) //Check this
ResultSet rs = st.executeQuery();
// If you are sure that is only one row then you nee to do
String columnX = null;
if (rs.next() != null) {
columnX = rs.getString(1); //Where 1 is the first column
}

update mysql database with jdbc

I have an error updating my database because of variables. This is my code:
UPDATE `payment` SET `paid`=1 AND `amoun`=$amountpaid WHERE `paid`=0 AND `userid`=$uid
$amountpaid is the amount of the bill that the user paid and $uid is user id. It seems like using $ in front of variable names is forbidden. How can I use variables in SQL?
Where are your variables coming from? You probably want something like this if you're using JDBC:
int setPaid = 1;
int amountPaid = x; // put $amountpaid here
int wherePaid = 0;
int userId = y; // put $uid here
String updateQuery = "UPDATE payment SET paid = ?, amoun = ?"
+ " WHERE paid = ? AND userid = ?";
PreparedStatement ps = con.prepareStatement(updateQuery);
ps.setInt(1, setPaid);
ps.setInt(2, amountPaid);
ps.setInt(3, wherePaid);
ps.setInt(4, userId);
ps.executeUpdate();
I got the solution by using String.
I converted the ArrayList to a String and then sent the data as string. The data got updated but I don't know what will happen next if I want to view the data in the client tier...